[英]axios: Unhandled Rejection (TypeError): Cannot read property 'error' of undefined
我正在嘗試使用 axios 發出 POST 請求。 以下是我在名為 userFunctions.js 的文件中的 axios function。
export const savePost = (postInfo) => {
return axios
.post(
"admin/savepost",
{ first_name: "hello", last_name: "world" },
{
headers: {
Authorization: `Bearer ${localStorage.usertoken}`,
},
}
)
.then((response) => {
console.log(response); //response is able to get printed here
console.log("axios:: saved post");
});
};
我在另一個名為 card.js 的文件中調用它,如下所示:
handleChange(e) {
e.preventDefault();
const { name, type, checked } = e.target;
if (type === "checkbox") {
this.setState({
[name]: checked,
});
savePost("post 1").then((res) => {
//response is undefined here!
console.log(res === undefined); //true
if (!res.error) {
console.log("client: post saved");
}
});
}
}
我收到以下錯誤:
未處理的拒絕(TypeError):無法讀取未定義的屬性“錯誤”
我不明白為什么響應能夠在 userFunctions.js 中打印但在我調用 card.js 中的 savePost 變量時未定義
發生這種情況是因為您在 userFunctions.js 中處理響應並且不將其返回(即then
在您的 promise 鏈中返回未定義)。 進行以下更改:
.then((response) => {
console.log(response); //response is able to get printed here
console.log("axios:: saved post");
return response
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.