我使用Node.js创建了一个CRUD REST API,并使用Postman进行测试。每当我使用Postman中的“Body”发送请求时,req.body返回undefine。可能是什么原因呢?
一个常见的错误是忘记安装body-parser NPM。
以下代码片段展示了如何使用Node.JS和Express创建简单的服务器和API。 首先安装NPM。
npm install body-parser express --save
然后尝试运行这段代码:
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.post('/test-url', (req, res) => {
console.log(req.body)
return res.send("went well")
})
app.listen(3000, () => {
console.log("running on port 3000")
})
早期版本的Express中包含了很多中间件。其中 bodyParser
是其中之一。当发布Express 4.0时,开发者决定将这些中间件从Express中分离出来,并制作成单独的包。在安装 bodyParser
模块后,语法从 app.use(express.json())
变为 app.use(bodyParser.json())
。
由于人们希望像以前一样将其捆绑到Express中,因此在4.16.0版中将 bodyParser
加回了Express。这意味着如果您使用最新版本,则不再需要使用 bodyParser.json()
,而可以改用 express.json()
。
对于那些感兴趣的人,4.16.0的发布历史可以在这里找到,而拉请求则在这里。
好了,回到正题,
你只需要添加以下代码:
app.use(express.json());
app.use(express.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
您的请求将由Express处理。:)
完整示例如下,
const express = require('express')
const app = express()
app.use(express.json())
app.use(express.urlencoded({ extended: true}));
app.post('/test-url', (req, res) => {
console.log(req.body)
return res.send("went well")
})
app.listen(3000, () => {
console.log("running on port 3000")
})
bodyParser
-- https://dev59.com/UVoT5IYBdhLWcg3wrA-5 - pfcodes