6

这是我的 MERN 应用程序中最奇怪的事情。当我从 Postman 向我的 api 执行 PUT 时,它可以工作并更新我的 api 和 mongoDB。在前端,即使控制台日志显示正确的值并且 url 相同,它也不会更新 api?任何帮助或指导将不胜感激......现在已经玩了好几天了。

邮递员证明更新工作

在此处输入图像描述 在此处输入图像描述

我的 axios 的代码如下:

handlePlayerSubmit(id, player) {
    console.log('This is the id: ' + id);
    console.log('This is the player: ' + player);

    let apiUrl = 'http://localhost:3001/api/teams';
    //sends the id and new author/text to our api
    axios.put(`${apiUrl}/${id}`, player).catch(err => {
      console.log(err);
    });

}

所以我知道它是由于控制台日志而触发的……不知道为什么它不更新 api?

它也不是 console.logging 一个错误。

开发工具中的网络屏幕截图

在此处输入图像描述

网络选项卡的标题:

在此处输入图像描述

在此处输入图像描述

4

2 回答 2

5

这是因为 Axios 将 JavaScript 对象序列化为 JSON。要以 application/x-www-form-urlencoded 格式序列化,您需要使用Axios 文档中描述的技术之一。

我认为qs对您来说是一个不错的解决方案:

let apiUrl = 'http://localhost:3001/api/teams';
//sends the id and new author/text to our api
axios.put(`${apiUrl}/${id}`, qs.stringify(player)).catch(err => {
  console.log(err);
});
于 2018-02-18T03:33:42.337 回答
1

Axios 不喜欢发布普通对象。

解决问题的一种方法是FormData

let formData = new FormData();
formData.append('param1', 'hi');
formData.append('param2', 'hello');

axios({
    method: 'POST',
    url: '/api/some-endpoint/',
    data: data
}).then(response => {
    console.log(response);
});

https://github.com/axios/axios/issues/1195

于 2020-01-20T18:43:35.020 回答