簡體   English   中英

NodeJS Express無法接收POST JSON

[英]NodeJS express can't receive POST json

我正在嘗試將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。

Express 4中的中間件和路由按照它們添加到您的應用程序的順序執行。 因此,您需要確保您的路由在使用bodyParser中間件之后。

JSON stringify從對象生成字符串。 采用

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

要么

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM