【问题标题】:axios.put is not working when sending query object发送查询对象时 axios.put 不起作用
【发布时间】:2022-02-14 12:51:54
【问题描述】:

我试图使用 axios 发送 put 请求以更新有关 mongodb 中一本书的信息,代码在使用 postman 时工作正常,但在提交时使用 react 组件内部使用的 axios.put 无法正常工作,而 axios.delete 是工作正常。我认为问题在于以这种方式发送查询对象不是正确的方式,但我无法找到解决方案。 这是handleSubmit的函数,

  • “id”是书的id

  • 'updates' 是一个状态对象,包含书籍数据中应该发生的所有更改。

  • 第二个函数handleChange是根据输入变化设置更新的函数

    const handleSubmit = async (e) => {
      e.preventDefault();
      try {
        const res = await axios.put("http://localhost:8000/book/edit/" + id, {
          params: {
            updates,
          },
        });
      setNewBook(res.data)
      } catch (err) {
        console.log(err);
      }
    };
    
       const handleChange = (e) => {
          e.preventDefault();
          const value = e.target.value;
          setUpdates({
            ...updates,
            [e.target.name]: value,
          });
        };
    

【问题讨论】:

  • 你好拉比!好像问题太笼统了。您是否收到任何错误或日志,URL 是否正确(http/https),您是否使用了代理(TCPMon)并查看发送的有效负载是什么以及发送到什么 URL
  • 这个问题经常出现!没人看the Axios docs吗?

标签: node.js reactjs express axios


【解决方案1】:

可能你误解了 axios put 方法。根据提供的 axios 文档 (https://github.com/axios/axios#axiosputurl-data-config),正确的结构是 axios.put(url[, data[, config]])

  • 第一个参数是URL
  • 第二个参数是数据(正文请求)。
  • 第三个参数是config(你把params留在这个参数里)

应该是这样的

const res = await axios.put("http://localhost:8000/book/edit/" + id, null, {
       params: {
         updates,
       },
     });

希望对你有帮助

【讨论】:

  • 谢谢,它在添加 (null) 和 (...updates) 而不是更新时有效
猜你喜欢
  • 2018-02-08
  • 2020-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-23
相关资源
最近更新 更多