【问题标题】:PUT request from React to mongodb with Axios使用 Axios 从 React 向 mongodb 发送请求
【发布时间】:2019-09-27 10:00:00
【问题描述】:

我需要一些帮助。当我使用 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);
        }
    }); 
    });

【问题讨论】:

    标签: node.js reactjs mongodb api axios


    【解决方案1】:

    这是因为您的 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"
      }            
    })
    

    【讨论】:

      猜你喜欢
      • 2022-01-18
      • 2023-03-31
      • 2019-11-24
      • 2021-10-30
      • 2019-04-24
      • 2022-10-21
      • 2021-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多