[英]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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.