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

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

有线索吗?


当前回答

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

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

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

其他回答

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

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

首先,确保你已经安装了名为'body-parser'的npm模块,调用:

npm install body-parser --save

然后确保在调用路由之前包含了以下行

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.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.

更新日期:2022年10月

首先使用以下步骤检查或添加主体解析器:

步骤:1 import bodyParser from body-parser

步骤2: app.use (bodyParser。Urlencoded ({extended: false})); app.use (bodyParser.json ());

步骤3:最重要的路由器应该在body解析器下面定义,这是body未定义....的主要原因

import noteRouter from "./src/routes/category_routes.js";

app.use(noteRouter);

无论你的名字定义在路由器取决于你..

希望这对你们有帮助