我对Stackoverflow这些垃圾问题感到很糟糕,但是花了几个小时寻找例子,我无法解决这个问题。
这就是了。我尝试用jQuery,我的代码是这样的
$.ajax ({
type: "PUT",
url: "http://localhost:3000/users/5a57adb130cdda747d2c4863",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(data),
success: function() {
console.log("worked!")
}
})成功函数被调用,但是当我使用postman时,我的数据没有改变。
但当我戴上邮差的时候,它就起作用了。
谢谢!
编辑:
在我的路径上进行调试时,JS代码似乎没有正确地传递数据。
路由代码
router.put('/:id', function (req, res) {
User.findByIdAndUpdate(req.params.id, req.body, {new: true}, function (err, user) {
if (err) return res.status(500).send("There was a problem updating the user.");
res.status(200).send(user);
console.log("PUT id:" + req.params.id);
console.log("PUT body:" + req.body.name); // .name being the data I am passing
console.log("PUT user:" + user)
});
});日志记录输出
PUT id:5a57adb130cdda747d2c4863
PUT body:undefined
PUT user:{ _id: 5a57adb130cdda747d2c4863,
name: 'fsafsafa',
... }
PUT id:5a57adb130cdda747d2c4863
PUT body:fsafsafa
PUT user:{ _id: 5a57adb130cdda747d2c4863,
name: 'fsafsafa',
... }发布于 2018-01-15 22:02:07
弄清楚了,你需要将router.use(bodyParser.json());添加到文件中!
https://stackoverflow.com/questions/48252916
复制相似问题