【发布时间】:2020-09-29 16:41:42
【问题描述】:
各位程序员们好,
我遇到了以下问题。我用 axios 做了一个 post 请求,如下所示:
componentDidMount() {
const config = {
headers: { Authorization: `Bearer ${Auth.getToken()}` },
};
const urlCategories = "http://localhost:8090/category";
axios.get(urlCategories, config).then((res) => {
const categories = res.data;
this.setState({ categories });
console.log(this.state.categories);
});
const urlTricks = "http://localhost:8090/trick/" + Auth.parseJwt().sub;
axios.get(urlTricks, config).then((res) => {
const tricks = res.data;
this.setState({ tricks });
console.log(this.state.tricks);
});
}
这行得通! :D
然后我想做同样的事,但后来,所以我几乎复制了这个但是...... 我得到了 401,而我看不出两者之间有任何真正的区别。我什至问过我的老师,他也不知道答案。
handleChecked = () => {
if (this.state.learned) {
this.setState(
{
learned: false,
},
() => {
console.log("Should be false and is: " + this.state.learned);
const config = {
headers: { Authorization: `Bearer ${Auth.getToken()}` },
};
axios
.post(
"http://localhost:8090/user/" +
Auth.parseJwt().sub +
"/" +
this.props.id +
"/" +
this.state.learned,
config
)
.then(() => {
console.log(this.props.name + " set to: " + this.state.learned);
});
}
);
} else { }
奇怪的是;它在 Postman 中工作,所以我的结论是前端一定有问题。后端应该没问题。如果你很好奇: Auth.parseJwt().sub 获取用户名(我知道这是一个奇怪的用户名名称)。另一个奇怪的事情是,当我复制 Chrome Inspect 概述中的 URL 并在 Postman 中使用它时,它可以工作......
有人知道或看到这段代码有什么问题吗?
【问题讨论】: