我正在Node.js上学习send host-name = gethostname();
来制作一个安静的api,而我在PUT和PATCH方法中遇到了一个问题,其中async/await
不能显示我想要的数据
下面是代码: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
和GET
。
i使用:
POST
我已经在我的app.js中设置了bodyparser中间件。但是仍然无法用于PATCH和PUT方法:(
请帮助我。我被卡住了。谢谢
答案 0 :(得分:0)
Nodejs无法识别req.body参数,为此,您需要将body-parser安装到项目中。 https://www.npmjs.com/package/body-parser
链接中有几个示例。
答案 1 :(得分:0)
您是否使用主体解析器读取请求主体?如果没有,请使用以下几行。
const bodyParser = require('body-parser');
app.use(bodyParser.json());
现在您可以通过req.body读取正文
答案 2 :(得分:0)
您可以使用express.json()
const app = express();
app.use(express.json());
答案 3 :(得分:0)
看起来像您没有用bodyParser填充req.body
需求主体
包含在请求正文中提交的键/值数据对。默认情况下,它是未定义的,并且在使用诸如body-parser和multer之类的用于解析正文的中间件时填充。
下面的示例演示如何使用正文解析中间件填充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
答案 4 :(得分:0)
[已解决] 最终我从req.body中获取了数据..问题是..我忘了检查邮递员的application / json中的标头。
对不起,..花时间帮助我解决问题:)
答案 5 :(得分:0)
我遇到了同样的问题,并尝试了来自 stackoverflow 的所有答案,但没有任何效果。最后我发现我正在以文本形式发送数据,该数据应该在 json 中。因此,如果您确定所做的一切都是正确的,请检查 postman 中的 body 部分并将数据类型更改为 json。