可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have this as configuration of my Express server
app.use(app.router); app.use(express.cookieParser()); app.use(express.session({ secret: "keyboard cat" })); app.set('view engine', 'ejs'); app.set("view options", { layout: true }); //Handles post requests app.use(express.bodyParser()); //Handles put requests app.use(express.methodOverride());
But still when I ask for req.body.something
in my routes I get some error pointing out that body is undefined
. Here is an example of a route that uses req.body
:
app.post('/admin', function(req, res){ console.log(req.body.name); });
I read that this problem is caused by the lack of app.use(express.bodyParser());
but as you can see I call it before the routes.
Any clue?
回答1:
You must make sure that you define all configurations BEFORE defining routes. If you do so, you can continue to use express.bodyParser()
.
An example is as follows:
var express = require('express'), app = express(), port = parseInt(process.env.PORT, 10) || 8080; app.configure(function(){ app.use(express.bodyParser()); app.use(app.router); }); app.listen(port); app.post("/someRoute", function(req, res) { console.log(req.body); res.send({ status: 'SUCCESS' }); });
回答2:
Latest versions of Express (4.x) has unbundled the middleware from the core framework. If you need body parser, you need to install it separately
npm install body-parser --save
and then do this in your code
var bodyParser = require('body-parser') var app = express() // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json())
回答3:
No. You need to use app.use(express.bodyParser())
before app.use(app.router)
. In fact, app.use(app.router)
should be the last thing you call.
回答4:
First make sure , you have installed npm module named 'body-parser' by calling :
npm install body-parser --save
Then make sure you have included following lines before calling routes
var express = require('express'); var bodyParser = require('body-parser'); var app = express(); app.use(bodyParser.json());
回答5:
As already posted under one comment, I solved it using
app.use(require('connect').bodyParser());
instead of
app.use(express.bodyParser());
I still don't know why the simple express.bodyParser()
is not working...
回答6:
The Content-Type in request header is really important, especially when you post the data from curl or any other tools.
Make sure you're using some thing like application/x-www-form-urlencoded, application/json or others, it depends on your post data. Leave this field empty will confuse Express.
回答7:
express.bodyParser() needs to be told what type of content it is that it's parsing. Therefore, you need to make sure that when you're executing a POST request, that you're including the "Content-Type" header. Otherwise, bodyParser may not know what to do with the body of your POST request.
If you're using curl to execute a POST request containing some JSON object in the body, it would look something like this:
curl -X POST -H "Content-Type: application/json" -d @your_json_file http://localhost:xxxx/someRoute
If using another method, just be sure to set that header field using whatever convention is appropriate.
回答8:
Looks like the body-parser is no longer shipped with express. We may have to install it separately.
var express = require('express') var bodyParser = require('body-parser') var app = express() // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json()) // parse application/vnd.api+json as json app.use(bodyParser.json({ type: 'application/vnd.api+json' })) app.use(function (req, res, next) { console.log(req.body) // populated!
Refer to the git page https://github.com/expressjs/body-parser for more info and examples.
回答9:
// Require body-parser (to receive post data from clients) var bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json())
回答10:
This occured to me today. None of above solutions work for me. But a little googling helped me to solve this issue. I'm coding for wechat 3rd party server.
Things get slightly more complicated when your node.js application requires reading streaming POST data, such as a request from a REST client. In this case, the request's property "readable" will be set to true and the POST data must be read in chunks in order to collect all content.
http://www.primaryobjects.com/CMS/Article144
回答11:
To work, you need to app.use(app.router) after app.use(express.bodyParser()), like that:
app.use(express.bodyParser()) .use(express.methodOverride()) .use(app.router);
回答12:
var bodyParser = require('body-parser'); app.use(bodyParser.json());
This saved my day.
回答13:
Wasted a lot of time:
Depending on Content-Type in your client request
the server should have different, one of the below app.use():
app.use(bodyParser.text({ type: 'text/html' })) app.use(bodyParser.text({ type: 'text/xml' })) app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) app.use(bodyParser.json({ type: 'application/*+json' }))
Source: https://www.npmjs.com/package/body-parser#bodyparsertextoptions
Example:
For me, On Client side, I had below header:
Content-Type: "text/xml"
So, on the server side, I used:
app.use(bodyParser.text({type: 'text/xml'}));
Then, req.body worked fine.
回答14:
In case if you post SOAP message you need to use raw body parser:
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); app.use(bodyParser.raw({ type: 'text/xml' }));
回答15:
Building on @kevin-xue said, the content type needs to be declared. In my instance, this was only occurring with IE9 because the XDomainRequest doesn't set a content-type, so bodyparser and expressjs were ignoring the body of the request.
I got around this by setting the content-type explicitly before passing the request through to body parser, like so:
app.use(function(req, res, next) { // IE9 doesn't set headers for cross-domain ajax requests if(typeof(req.headers['content-type']) === 'undefined'){ req.headers['content-type'] = "application/json; charset=UTF-8"; } next(); }) .use(bodyParser.json());
回答16:
Credit to @spikeyang for the great answer (provided below). After reading the suggested article attached to the post, I decided to share my solution.
When to use?
The solution required you to use the express router in order to enjoy it.. so: If you have you tried to use the accepted answer with no luck, just use copy-and-paste this function:
function bodyParse(req, ready, fail) { var length = req.header('Content-Length'); if (!req.readable) return fail('failed to read request'); if (!length) return fail('request must include a valid `Content-Length` header'); if (length > 1000) return fail('this request is too big'); // you can replace 1000 with any other value as desired var body = ''; // for large payloads - please use an array buffer (see note below) req.on('data', function (data) { body += data; }); req.on('end', function () { ready(body); }); }
and call it like:
bodyParse(req, function success(body) { }, function error(message) { });
NOTE: For large payloads - please use an array buffer (more @ MDN)