jQuery 放不工作,但与邮递员一起工作

jQuery Put not working, but works with postman

我觉得用这些垃圾问题来处理 Whosebug 很糟糕,但是经过数小时的查找示例,我无法解决问题。

在这里。我正在尝试使用 jQuery 进行 PUT,我的代码是这样

$.ajax ({
  type: "PUT",
  url: "http://localhost:3000/users/5a57adb130cdda747d2c4863",
  dataType: "json",
  contentType: "application/json",
  data: JSON.stringify(data),
  success: function() {
    console.log("worked!")
  }
})

调用了成功函数,但是当我在邮递员上GET时,我的数据没有改变。

但是当我使用 postman 时,它起作用了。

Postman screenshot

谢谢!!!

编辑:

在我的路线上进行调试后,似乎 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',
  ... }

明白了,你需要在文件中添加router.use(bodyParser.json());