Nodejs - Req.body undefined in post with expression 4.9.0

I'm a newbie nodejs, I'm trying to find out req.body using middleware syntax parsing or not using anything, but both req.body found are undefined. Here is my code

var app = require('express')(); var bodyParser = require('body-parser'); var multer = require('multer'); app.get('/', function(req, res) { res.send("Hello world!\n"); }); app.post('/module', function(req, res) { console.log(req); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(multer); console.log(req.body); }); app.listen(3000); module.exports = app; 

And I use the command curl -X POST -d 'test case' http://127.0.0.1:3000/module to test it.

express version: 4.9.0
node version: v0.10.33

Please help, thanks.

+6
source share
3 answers

By default, cURL uses Content-Type: application/x-www-form-urlencoded for form submissions that do not contain files.

For forms with urlencoded, your data must be in the correct format: curl -X POST -d 'foo=bar&baz=bla' http://127.0.0.1:3000/module or curl -X POST -d 'foo=bar' -d 'baz=bla' http://127.0.0.1:3000/module .

For JSON, you need to explicitly set the correct Content-Type : curl -H "Content-Type: application/json" -d '{"foo":"bar","baz":"bla"}' http://127.0.0.1:3000/module .

Also, as @Brett pointed out, you need app.use() your middleware to this POST route somewhere (outside the route handler).

+5
source

You are placing the express configuration for body-parser in the wrong place.

 var app = require('express')(); var bodyParser = require('body-parser'); var multer = require('multer'); // these statements config express to use these modules, and only need to be run once app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(multer); // set up your routes app.get('/', function(req, res) { res.send("Hello world!\n"); }); app.post('/module', function(req, res) { console.log(req); console.log(req.body); }); app.listen(3000); module.exports = app; 
+5
source

You must ensure that you define all express configurations before defining routes. since the parser body is responsible for parsing the request body.

 var express = require('express'), app = express(), port = parseInt(process.env.PORT, 10) || 8080; //you can remove the app.configure at all in case of it is not supported //directly call the inner code app.configure(function(){ app.use(bodyParser.urlencoded()); //in case you are sending json objects app.use(bodyParser.json()); app.use(app.router); }); app.listen(port); app.post("/module", function(req, res) { res.send(req.body); }); 
+1
source

Source: https://habr.com/ru/post/979628/


All Articles