[英]node js async/await : why i can't get the data ? req.body
我正在 Node.js 学习async/await
以制作一个安静的 api,我在 PUT 和 PATCH 方法中遇到了问题,对于req.body
它无法显示我想要的数据
这是代码: controllers/users
replaceUser: async (req, res, next) => {
//enforce that req.body must contain all the fields
const { userId } = req.params;
const newUser = req.body;
// const result = await User.findByIdAndUpdate(userId, newUser, {new: true}).exec();
// console.log(result)
console.log(newUser)
console.log(userId)
// res.status(200).json(result);
// console.log(userId, newUser)
},
和这个路由器代码:
router.route('/:userId')
.get(UsersController.getUser)
.put(UsersController.replaceUser)
.patch(UsersController.updateUser)
当我启用findone
调试时,只有findone
函数处于活动状态,并且此方法适用于GET
和POST
。
我使用:
"body-parser": "^1.18.3",
"express": "^4.16.3",
"express-promise-router": "^3.0.3",
"mongoose": "^5.3.1",
我已经在我的 app.js 中设置了 bodyparser 中间件 .. 但仍然不适用于 PATCH 和 PUT 方法:(
请帮我。 我被困住了。 谢谢你
看起来你没有正确地用 bodyParser 填充 req.body
这是取自快递网站
请求体
包含请求正文中提交的数据的键值对。 默认情况下,它是未定义的,并在您使用 body-parser 和 multer 等正文解析中间件时填充。
下面的例子展示了如何使用 body-parsing 中间件来填充 req.body。
var app = require('express')();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
replaceUser: async (req, res, next) => {
//enforce that req.body must contain all the fields
const { userId } = req.params;
const newUser = req.body;
// const result = await User.findByIdAndUpdate(userId, newUser, {new: true}).exec();
// console.log(result)
console.log(newUser)
console.log(userId)
// res.status(200).json(result);
// console.log(userId, newUser)
}
记笔记:
app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
[已解决] 最后我从 req.body 得到了我的数据。
对不起,伙计们.. 花点时间帮助我的问题:)
我遇到了同样的问题,并尝试了 stackoverflow 的所有答案,但没有任何效果。 最后我发现我正在以文本形式发送数据,该数据应该在 json 中。 因此,如果您确定所做的一切都是正确的,请检查 postman 中的 body 部分并将数据类型更改为 json。
Nodejs 无法识别 req.body 参数,为此您需要将 body-parser 安装到您的项目中。 https://www.npmjs.com/package/body-parser
链接中有几个例子。
您是否使用 body-parser 来读取请求正文? 如果没有,请使用以下几行..
const bodyParser = require('body-parser');
app.use(bodyParser.json());
现在你可以通过 req.body 读取正文
您可以使用 express.json()
const app = express();
app.use(express.json());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.