Express: Req.body is undefined after POST req

♀尐吖头ヾ 提交于 2019-12-11 04:06:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!