Reputation: 439
I am going nuts on this, I have spent hours on Stackoverflow and the net in general, tried this that and the other, and still cannot get a result.
I'm a (very) newb on node.js, but have successfully followed a tutorial to build a (very) simple form using bodyParser.urlencoded
, and I can successfully recover and display the posted data. Now I want to do the same using bodyParser.json()
- but no matter what I try, the result is always empty.
Here is the code:
var express = require('express');
var session = require('cookie-session');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var jsonParser = bodyParser.json();
var app = express();
// JSON testing
app.post('/json-test', jsonParser, function(req, res) {
if (!req.body) return res.sendStatus(400);
console.log(JSON.stringify(req.body));
console.log(req.body.title);
res.status(200).send(req.body.title);
})
// Can't get anything else
.use(function(req, res, next){
res.setHeader('Content-Type', 'text/plain');
res.status(404).send('Page introuvable !');
})
.listen(8090);
Here is the curl request
$curl -X POST -H "application/json" -d '{"title":"test-title"}' http://localhost:8090/json-test
The result of the first console.log is {}
and of the second just undefined
.
What am I doing wrong?
Upvotes: 0
Views: 272
Reputation: 29172
You have incorrect curl request, need add "Content-Type":
curl -X POST -H "Content-Type: application/json" \
-d '{"title":"test-title"}' http://localhost:8090/json-test
Upvotes: 1