我用nodejs创建了一个crud rest api,正在用postman测试这个api。每当我在postman中使用"Body“发送请求时,req.body都会返回undefine。请问是什么原因造成的?
发布于 2018-12-17 08:21:09
一个常见的错误是忘记了主体解析器NPM。
下面的代码展示了使用Node.JS和Express创建服务器和应用程序接口是多么简单。首先安装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")
})
发布于 2021-10-18 09:39:57
历史:
Express的早期版本曾经捆绑了许多中间件。bodyParser
是随附的中间件之一。当Express 4.0发布时,他们决定从Express中移除捆绑的中间件,并将它们单独打包。在安装bodyParser
模块之后,语法从app.use(express.json())
更改为app.use(bodyParser.json())
。
bodyParser
在版本4.16.0中被重新添加到Express中,因为人们希望像以前一样将它与Express捆绑在一起。这意味着如果您使用的是最新版本,则不必再使用bodyParser.json()
。您可以改用express.json()
。
对于感兴趣的人,4.16.0的发布历史是here,拉取请求是here。
好了,回到正题,
实施:
你所要做的就是添加,
app.use(express.json());
app.use(express.urlencoded({ extended: true}));
在路由声明之前,而不是,
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
快递将处理您的请求。:)
完整的示例如下所示:
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")
})
https://stackoverflow.com/questions/53807707
复制