Express:POST请求后,req.body是未定义的 [英] Express: Req.body is undefined after POST req

查看:140
本文介绍了Express:POST请求后,req.body是未定义的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Node JS的新手. 我对职位要求不确定.我的快递版本是4.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);
});

在内容长度方面,我得到了234. 谢谢!!

In content-length I am getting 234. Thanks!!

推荐答案

对于将来的访问者-@mscdex的建议似乎导致@Rahul更改了调用其API的客户端,以便其将application/json作为Content-Type标头.另一种选择是更改body-parser尝试解析的Content-Type标头.

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.

您可以通过指定type来配置body-parser以接受其他Content-Type,如下所示:

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' }));

这是对我有用的解决方案,用于解析从Ember应用发送的JSON.我觉得最好更改body-parser接受的默认Content-Type标头,而不是更改应用程序周围的其余工具.

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.

这篇关于Express:POST请求后,req.body是未定义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆