Comments (12)
That works just fine for me. Can you provide some more details, like what isn't working, or what the error is, or what the parse looks like to you?
from body-parser.
console.log(req.body)
simply returns {}
.
The full route looks like this:
var router = express.Router();
var validator = require('express-validator');
router.use(validator());
var jsonParser = bodyParser.json({ type: 'application/*+json' } );
router.post('/create-account', jsonParser, function(req, res) {
console.log(req.body); // This returns {}
if (!req.body) return res.sendStatus(400);
req.checkBody('userName', 'required').notEmpty();
req.checkBody('name', 'required').notEmpty();
var errors = req.validationErrors();
if (errors) {
res.status(400).send('There have been validation errors: ' + util.inspect(errors));
return;
}
I know body-parser has nothing to do with validation(used express-validator), but since you asked for details, on validation, the json fields couldn't be validated because req.body
returns empty.
There have been validation errors: [ { param: 'userName', msg: 'required', value: undefined }, { param: 'name', msg: 'required', value: undefined }]
from body-parser.
Gotcha. It would seem the reason req.body = {}
for your case is because of one of two reasons (both of which I cannot confirm because will app code wasn't pasted):
- The request's content-type is not
application/stuff+json
; if it is justapplication/json
then yourjsonParser
will ignore it - The
jsonParser
you have there will only ever work as long as something prior to your code is not reading the bdoy, as in perhaps somewhere outside what you posted there is aapp.use(bodyParser)
or similar?
The following code works perfectly fine for me:
var app = express();
var router = express.Router();
var jsonParser = bodyParser.json({ type: 'application/*+json' } );
router.post('/create-account', jsonParser, function(req, res) {
console.log(req.body);
});
app.use(router);
app.listen(3000);
from body-parser.
Thanks
I don't have app.use(bodyParser())
anywhere in my code. Moreso, I'm reading the json data from a file like so:
curl -v -H "Content-Type: application/json" -d @/tmp/create-account.json http://localhost:3000/auth/create-account
Could it be that there's something wrong with how the request is constructed? What's your request content-type?
from body-parser.
Could it be that there's something wrong with how the request is constructed?
Ah. Your cURL command has the wrong content type, as application/json
does not match application/*+json
. You need to change one or the other. If you want to use application/json
, then set that in your code, otherwise send a content-type in cURL that matches application/*+json
.
What's your request content-type?
I used application/stuff+json
as stated above.
from body-parser.
Okay. I simply changed the request to curl -v -d @/tmp/create-account.json http://localhost:3000/auth/create-account
and code as:
var urlencodedParser = bodyParser.urlencoded({extended: false } );
router.post('/create-account', urlencodedParser, function(req, res) {
console.log(req.body);
});
from body-parser.
Well, just for enhancement purposes for the library, a request like so:
curl -v -H "Content-Type: application/json" -d @/tmp/create-account.json http://localhost:3000/auth/create-account
and code like so:
var jsonParser = bodyParser.json({ type: 'application/json' } );
router.post('/create-account', jsonParser, function(req, res) {
console.log(req.body)
});
gives this error:
SyntaxError: Unexpected token }
at Object.parse (native)
at parse (/Users/osx/projects/nodescripts/useraccountservice/node_modules/body-parser/lib/types/json.js:84:17)
at /Users/osx/projects/nodescripts/useraccountservice/node_modules/body-parser/lib/read.js:102:18
at IncomingMessage.onEnd (/Users/osx/projects/nodescripts/useraccountservice/node_modules/body-parser/node_modules/raw-body/index.js:136:7)
at IncomingMessage.g (events.js:180:16)
at IncomingMessage.emit (events.js:92:17)
at _stream_readable.js:943:16
at process._tickCallback (node.js:419:13)
from body-parser.
It's because you're sending invalid JSON.
from body-parser.
Feel fee to post the contents of /tmp/create-account.json
and I can point out where the JSON is invalid (you can always check yourself by running the file through JSON.parse
, part of core JavaScript.
from body-parser.
{
"schemas":["urn:scim:schemas:core:1.0"],
"userName":"bjensen",
"name":{
"formatted":"Ms. Barbara J Jensen III",
"familyName":"Jensen",
"givenName":"Barbara"
},
"emails":[{
"type":"home",
"value":"[email protected]"
}],
}
from body-parser.
That very last trailing comma is illegal is JSON.
from body-parser.
Awesome. Merci!
from body-parser.
Related Issues (20)
- HTTP:413 Request Entity Too Large HOT 5
- Conform with express-validator on parameter representation
- bodyParser is deprecated, error HOT 1
- bodyparser.json() shown as deprecated? (question) HOT 7
- pass options to qs thru urlencoded? HOT 4
- Cannot catch SyntaxError when user provides invalid JSON in body and content-type: application/json HOT 3
- Support for content-encoding: deflate raw HOT 7
- req.body could not be accessed when send as form data, but works fine with JSON HOT 3
- Pass custom parameters to `qs` HOT 3
- Update iconv-lite to latest 0.6.3 HOT 7
- support for ndjson
- Regular Expression Denial of Service (ReDoS) in [email protected] HOT 3
- Update `debug` dependency (memory leak leading to vulnerability) HOT 1
- api calls made with invalid json HOT 5
- Add support for removing body parser limit HOT 8
- BadRequestError: request size did not match content length HOT 7
- How to handle content-type mismatch? HOT 1
- CVE-2017-20165 - debug HOT 2
- Issue HOT 1
- Debug package version in body parser showing security vulnerability HOT 10
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from body-parser.