簡體   English   中英

jQuery Put不起作用,但可以與郵遞員一起使用

[英]jQuery Put not working, but works with postman

對於這些垃圾問題,我感到很沮喪,但經過數小時的示例查找后,我無法解決問題。

這里是。 我正在嘗試使用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!")
  }
})

成功函數被調用,但是當我在郵遞員上獲取時,我的數據沒有改變。

但是當我把郵遞員放進去時,它就可以了。

郵差截圖

謝謝!!!

編輯:

在我的路線上進行調試后,似乎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()); 到文件!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM