NodeJS express可以't接收POST json

NodeJS express can't receive POST json

本文关键字:接收 POST json express 可以 NodeJS      更新时间:2023-09-26

我正在尝试将JSON发送到我的NodeJS路由。

curl -H "Content-Type: application/json" -d '{"name":"homer"}' http://localhost:3000/api

所以,在我的server.js:中

...
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json({extended:true}));
app.use(methodOverride('_method'));
...

然后,在我的路线上:

router.post('/api', function (req, res){
    console.log(req.body);
});

因此,输出显示undefined

我做错什么了吗?我正在使用Express v4。

Express4中的中间件和路由按照添加到应用程序的顺序执行。因此,您需要确保您的路由在使用bodyParser中间件之后。

JSON字符串从对象生成一个字符串。使用

 JSON.parse({"name":"homer"})

 $.param({"name":"homer"})