user3175226
user3175226

Reputation: 3659

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.

Upvotes: 1

Views: 279

Answers (2)

mscdex
mscdex

Reputation: 106698

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.

Upvotes: 2

T00rk
T00rk

Reputation: 2287

JSON stringify makes a string from object. Use

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

or

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

Upvotes: 0

Related Questions