简体   繁体   中英

NodeJS express can't receive POST json

I'm trying to send a JSON to my NodeJS route.

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

So, in my server.js:

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

Then, in my route:

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

So, the output shows undefined

Am I doing something wrong? I'm using Express v4.

Middleware and routes in Express 4 are executed in the order they're added to your app. So you need to make sure that your routes come after your bodyParser middlewares are used.

JSON stringify makes a string from object. Use

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM