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

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

有线索吗?


当前回答

大部分时间需要。由于缺少JSON解析器,body未定义

const express = require('express');
app.use(express.json());

可能缺少体解析器

const bodyParser  = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));

有时由于cros原点没有定义,所以加起来

const cors = require('cors');
app.use(cors())

其他回答

根据@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());

不。你需要在app.use(app.router)之前使用app.use(express.bodyParser())。实际上,app.use(app.router)应该是你调用的最后一个东西。

在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对象。

正如已经发布在一个评论下,我解决了它使用

app.use(require('connect').bodyParser());

而不是

app.use(express.bodyParser());

我仍然不知道为什么简单的express.bodyParser()不工作…

试试这个

npm i multer --save
const express = require('express');
const multer  = require('multer');
const upload = multer();
const app = express();

app.post('/test', upload.any(), (req, res) => {
  console.log('data', req.body);
  res.setHeader('Content-Type', 'application/json');
  res.send(req.body);
});