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

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

有线索吗?


当前回答

简单的例子,通过所有:

方法='post'登录后的快捷代码:

这将不需要任何这样的bodyParser()。

app.js

const express = require('express');
const mongoose = require('mongoose');
const mongoDB = require('mongodb');

const app = express();

app.set('view engine', 'ejs');

app.get('/admin', (req,res) => {
 res.render('admin');
});

app.post('/admin', (req,res) => {
 console.log(JSON.stringify(req.body.name));
 res.send(JSON.stringify(req.body.name));
});

app.listen(3000, () => {
 console.log('listening on 3000');
});

admin.ejs

<!DOCTYPE Html>
<html>
 <head>
  <title>Admin Login</title>
 </head>
 <body>
   <div>
    <center padding="100px">
       <form method="post" action="/admin">
          <div> Secret Key:
            <input name='name'></input>
          </div><br></br><br></br>
          <div>
            <button type="submit" onClick='smsAPI()'>Get OTP</button>
          </div>
       </form>
    </center>
    </div >
</body>
</html>

你得到输入。“”中的“name”是一个通过method='post'传递数据的变量。对于多个数据输入,name='name[]'。

因此,

on name='name' 

input: Adu
backend: "Adu"

OR

input: Adu, Luv,
backend: "Adu, Luv,"

on

name='name[]'
input: Adu,45689, ugghb, Luv
backend: ["Adu,45689, ugghb, Luv"]

其他回答

express.bodyParser()需要被告知它正在解析的内容类型。因此,您需要确保在执行POST请求时,包含了“Content-Type”标头。否则,bodyParser可能不知道如何处理POST请求的主体。

如果你使用curl来执行一个POST请求,其中包含一些JSON对象,它看起来会像这样:

curl -X POST -H "Content-Type: application/json" -d @your_json_file http://localhost:xxxx/someRoute

如果使用其他方法,请确保使用合适的约定设置报头字段。

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

最新版本的Express (4.x)将中间件从核心框架中分离出来。如果需要正文解析器,则需要单独安装它

npm install body-parser --save

然后在代码中这样做

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

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

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

问题得到了解答。但由于它是相当通用和要求。body未定义是一个常见的错误,特别是对于初学者,我发现这是恢复我所知道的关于这个问题的最好地方。


此错误可能由以下原因引起:

1. [服务器端][经常]忘记或误用解析器中间件

您需要使用适当的中间件来解析传入的请求。例如,express.json()以JSON格式解析请求,express.urlencoded()以urlencoded格式解析请求。

const app = express();
app.use(express.urlencoded())
app.use(express.json())

您可以在express文档页面中看到完整的列表

如果在Express中找不到适合请求的解析器(XML、form-data…),就需要为它找到另一个库。例如,要解析XML数据,可以使用这个库 您应该在路由声明部分之前使用解析器中间件(我做了一个测试来确认这一点!)中间件可以在初始化express app后立即配置。 像其他答案指出的那样,bodyParser自express 4.16.0以来就已弃用,您应该像上面那样使用内置中间件。

2. [客户端][很少]忘记随请求一起发送数据

你需要发送数据…

要验证数据是否已随请求一起发送,请打开浏览器的devtools中的Network选项卡并搜索您的请求。

这种情况很少见,但我看到一些人试图在GET请求中发送数据,因为GET请求请求。Body未定义。

3.[服务器和客户端][经常]使用不同的内容类型

Server and client need to use the same Content-Type to understand each other. If you send requests using json format, you need to use json() middleware. If you send a request using urlencoded format, you need to use urlencoded()... There is 1 tricky case when you try to upload a file using the form-data format. For that, you can use multer, a middleware for handling multipart/form-data. What if you don't control the client part? I had a problem when coding the API for Instant payment notification (IPN). The general rule is to try to get information on the client part: communicate with the frontend team, go to the payment documentation page... You might need to add appropriate middleware based on the Content-Type decided by the client part.

最后,给全栈开发者一个建议:)

当遇到这样的问题时,尝试使用一些API测试软件,如Postman。目标是消除客户端部分的所有噪声,这将帮助您正确识别问题。

在Postman中,一旦得到正确的结果,就可以使用软件中的代码生成工具来获得相应的代码。按钮</>在右边栏上。你有很多流行语言/库的选择…