使用Axios从React到mongodb的PUT请求

时间:2019-05-09 14:21:42

标签: node.js reactjs mongodb api axios

我需要一些帮助。当我使用Axios从React应用发送请求时,PUT请求不起作用。但是,当我从Postman测试PUT api时-它的工作原理与预期相同。服务器端-node + mongoose + mongodb。

modifyCurrentHaspInfo = (e) => { 
      if (prompt("Enter password:") === "123456") {
        axios.put("/hasp/change", {
          data: {
            _id: "5cd40f6f1e922c236caa82f4",
            serial: "11111-22222",
            soft: "test-put"
            }            
          })
        .then((res) => {
          console.log(res.data);      
        })
        .catch((err) => {
          console.log(err);
        })
      } else {
        alert("Wrong password!");
      }         
   }

找到正确的ID后,必须更改正文中的数据。这是来自服务器的代码:

//PUT request
app.put("/hasp/change", function(req, res) {
    //console.log(req.body);
    HaspInfo.findOneAndUpdate({_id: req.body._id}, {$set:req.body}, {new: true}, function(err, hasps) {
        if (err) {
            res.status(500).send({error: "Could not modify hasp info..."});
        } else {           
           //console.log(hasps);
           res.status(200).send(hasps);
        }
    }); 
    });

1 个答案:

答案 0 :(得分:0)

这是因为您的axios格式不正确(不是您在后端所期望的)。

现在可以从后端访问从axios发送数据的方式

req.body.data

// which will be an object like
{
  _id: "5cd40f6f1e922c236caa82f4",
  serial: "11111-22222",
  soft: "test-put"
}

因此可以像_id一样访问req.body.data._id。将您的请求更改为以下内容之一(注意差异)

axios.put("/hasp/change", {
  _id: "5cd40f6f1e922c236caa82f4",
  serial: "11111-22222",
  soft: "test-put"
})

axios.put({
  url: "/hasp/change",
  data: {
    _id: "5cd40f6f1e922c236caa82f4",
    serial: "11111-22222",
    soft: "test-put"
  }            
})
相关问题