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

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.js(或index.js)文件的路由之前编写这段代码。

app.use(bodyParser.urlencoded({ extended: true }));
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);

使用这一行在任何get或post请求之前在顶部进行适当的解析:

app.use(express.json()) 

它将json数据解析为Javascript对象。

在express 4及以上版本中,你不需要body解析器,它们有自己的json解析方法, 在您的express应用程序的高设置级别添加

var express = require('express');
var app = express()
app.use(express.json()); //declare this to receive json objects.

其他答案没有提到,当通过fetch或其他客户端进行表达请求时。请求必须以某种方式格式化。

const response = await fetch(`${expressAddress}/controller/route`, { 
      method: 'POST', // *GET, POST, PUT, DELETE, etc.
      headers: {
          'Content-Type': 'application/json' //this must be set to a json type
      },
      body: JSON.stringify(row) //regular js object need to be converted to json
  })

如果你像这样进行取回请求。Body将按预期输出json对象。

必须设置报头内容类型为application/json,以便从POST方法接收原始内容在邮差哪里

以防有人遇到和我一样的问题;我使用一个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);