jQuery不工作,但与邮递员合作

时间:2018-01-14 18:42:01

标签: jquery rest api express put

我对这些垃圾问题感到很糟糕,但是几个小时寻找例子,我无法解决问题。

在这里。我试图用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 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',
  ... }

1 个答案:

答案 0 :(得分:0)

想出来,你需要将router.use(bodyParser.json());添加到文件中!