问题
I am new to node JS. I am getting undefined for post request. My express version is 4.10. I think I am missing something.
var express = require('express');
var http = require('http');
var app = express();
app.use(express.static(__dirname + '/public'));
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.post('/test',function(req,res){
var color1 = req.body.color;
console.log(req.headers);
console.log("Color : "+color1);
});
In content-length I am getting 234.
Thanks!!
回答1:
For future visitors - it seems that @mscdex's suggestion lead @Rahul to change the client calling his API so that it passed application/json as the value for the Content-Type header. Another option is to change the Content-Type header that body-parser attempts to parse.
You can configure body-parser to accept a different Content-Type by specifying the type it accepts as follows:
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
This is the solution that worked for me in order to parse the JSON sent from an Ember app. I felt it was better to change the default Content-Type header accepted by body-parser than changing the rest of the tooling around my application.
来源:https://stackoverflow.com/questions/27848500/express-req-body-is-undefined-after-post-req