Express 4.17 req body 为空
Express 4.17 req body is empty
req.body
总是空的。
index.js:
const express = require('express');
const app = express();
const port = 8080;
app.use(express.static('public'))
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const userRoutes = require('./routes/user.routes');
app.use("/user", userRoutes);
app.listen(port, () => console.log("app listening."));
routes/user.路线:
const express = require('express');
const router = express.Router();
router.post('/', (req, res) => {
res.json({ requestBody: req.body });
});
module.exports = router;
客户端脚本:
fetch('/user', {
method: 'POST',
body: JSON.stringify({ testData: "testData" }),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
})
.then(function(response) {
return response.json();
})
.then(function(responseData) {
console.log(responseData);
})
.then(function(result) {
if (result.error) {
alert(result.error.message);
}
});
在控制台中获取的结果:
{requestBody: {}}
来自 docs for req.body
By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.
所以你需要使用一个中间件来填充 req.body
const bodyParser = require('body-parser')
router.use(bodyParser.json())
router.post('/', (req, res) => {
res.json({ requestBody: req.body });
});
确保使用此命令在本地安装最新的 Express 版本:
npm i -S express
如果问题仍然存在,请尝试使用其他浏览器
req.body
总是空的。
index.js:
const express = require('express');
const app = express();
const port = 8080;
app.use(express.static('public'))
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const userRoutes = require('./routes/user.routes');
app.use("/user", userRoutes);
app.listen(port, () => console.log("app listening."));
routes/user.路线:
const express = require('express');
const router = express.Router();
router.post('/', (req, res) => {
res.json({ requestBody: req.body });
});
module.exports = router;
客户端脚本:
fetch('/user', {
method: 'POST',
body: JSON.stringify({ testData: "testData" }),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
})
.then(function(response) {
return response.json();
})
.then(function(responseData) {
console.log(responseData);
})
.then(function(result) {
if (result.error) {
alert(result.error.message);
}
});
在控制台中获取的结果:
{requestBody: {}}
来自 docs for req.body
By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.
所以你需要使用一个中间件来填充 req.body
const bodyParser = require('body-parser')
router.use(bodyParser.json())
router.post('/', (req, res) => {
res.json({ requestBody: req.body });
});
确保使用此命令在本地安装最新的 Express 版本:
npm i -S express
如果问题仍然存在,请尝试使用其他浏览器