【发布时间】:2020-06-14 20:53:09
【问题描述】:
我正在尝试使用 axios 发出 POST 请求。以下是我在名为 userFunctions.js 的文件中的 axios 函数。
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 变量时未定义
【问题讨论】:
标签: javascript reactjs axios