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

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())引起的;但你可以看到,我把它叫做路线之前。

有线索吗?


当前回答

var bodyParser = require('body-parser');
app.use(bodyParser.json());

这帮了我大忙。

其他回答

以防有人遇到和我一样的问题;我使用一个url前缀像

http://example.com/api/

哪一个是用路由器设置的

app.use('/api', router); 

然后我有了以下内容

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

修复我的问题是将bodyparser配置放在app.use('/api', router)之上;

最后

// setup bodyparser
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));

//this is a fix for the prefix of example.com/api/ so we dont need to code the prefix in every route
    app.use('/api', router); 
// 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())

在我的例子中,这是因为在包含路由之后使用了body-parser。

正确的代码应该是

app.use(bodyParser.urlencoded({extended:true}));
app.use(methodOverride("_method"));
app.use(indexRoutes);
app.use(userRoutes);
app.use(adminRoutes);

当我使用bodyParser时,它被标记为已弃用。为了避免这种情况,我使用下面的代码和express代替bodyParser。

注意:路由必须声明,最后这很重要!这里的其他回答很好地描述了这个问题。

const express = require("express");
const app = express();

const routes = require('./routes/api');

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// Routes must declared finally
app.use('/', routes);

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

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

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