我有这个作为我的快速服务器的配置

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());

但是当我在我的路由中请求req.body.something时,我得到了一些错误,指出body是未定义的。下面是一个使用req的路由示例。身体:

app.post('/admin', function(req, res){
    console.log(req.body.name);
});

我读到这个问题是由缺乏app.use(express.bodyParser())引起的;但你可以看到,我把它叫做路线之前。

有线索吗?


当前回答

我用:

app.post('/', bodyParser.json(), (req, res) => {//we have req.body JSON
});

其他回答

你可以试着在顶部添加这行代码(在require语句之后):

app.use(bodyParser.urlencoded({extended: true}));

至于为什么它起作用的原因,请查看文档:https://www.npmjs.com/package/body-parser#bodyparserurlencodedoptions

根据@kevin-xue所说,需要声明内容类型。在我的实例中,这只发生在IE9中,因为XDomainRequest不设置内容类型,所以bodyparser和expressjs忽略了请求的主体。

我通过在将请求传递给主体解析器之前显式地设置content-type来解决这个问题,如下所示:

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());
You have to check following things for that:-
1. app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())
Implement body parser in your app.

2. Check headers in postman its should be based on your rest api's, like if your Content-Type: application/json it should be defined in your postman headers.

我的是一个文本输入,我在这里添加了这个答案,所以它会帮助人们。确保在解析时设置了编码!我努力让它工作,直到我给它设置了一个合适的值。

这是我在没有使用任何解析器的情况下得到的错误:

error info: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.

Received an instance of undefined at Function.from (buffer.js:327:9)

我们现在不必像其他人已经提到的那样在Express中使用body解析器,而只需使用app.use(Express .text());没能解决我的问题。

undefined现在变成了Object。根据Express文档,如果Content-Type不匹配(在其他情况下),请求主体将返回一个空对象({})。

error info: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.

Received an instance of Object at Function.from (buffer.js:327:9)

您设置的编码类型也需要正确。在我的例子中,它是文本/纯文本。您可以更改它以满足您的需要,如JSON等。我这样做了,瞧!效果好极了!

app.use(express.text({
    type: "text/plain" 
}));

感谢@spikeyang的精彩回答(如下所示)。在阅读了这篇文章后,我决定分享我的解决方案。

什么时候使用?

解决方案要求你使用快速路由器才能享受它。所以: 如果你试图使用已接受的答案,但运气不好,只需使用复制粘贴这个函数:

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

叫它:

bodyParse(req, function success(body)
{

}, function error(message)
{

});

注意: 对于大的有效载荷-请使用数组缓冲区(更多@ MDN)