繁体   English   中英

将作品放入 Postman 而不是 AXIOS

[英]Put works in Postman but not AXIOS

这是我的 MERN 应用程序中最奇怪的事情。 当我从 Postman 执行 PUT 到我的 api 时,它会工作并更新我的 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 错误。

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

在此处输入图片说明

来自网络选项卡的标题:

在此处输入图片说明

在此处输入图片说明

这是因为 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);
});

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM