我在React / Vue中执行相同的登录功能。 它在VueJS上工作正常,但是当我在ReactJS中使用时,它不起作用。
Vue工作正常:
async EnvioLogin() {
try {
const response = await axios.post("api/auth/login", {
email: this.email,
password: this.password,
});
localStorage.setItem("token", response.data.token);
if (response.status == "200") {
this.getUsers();
console.log(response);
this.$router.push("intermediorotas");
this.showLogin = false;
}
} catch (error) {
this.showError = true;
setTimeout(() => {
this.showError = false;
}, 2000);
}
},
},
反应不起作用:
EnvioLogin = async () => {
try {
const response = await axios.post("api/auth/login", { email: this.state.email, password: this.state.password });
localStorage.setItem("token", response.data.token);
if (response.status === "200") {
this.getUsers();
console.log(response);
this.props.history.push("/app");
}
} catch (error) {
this.setState({ error: "User or Password wrong!" });
setTimeout(() => {
this.setState({ error: "" });
}, 2000);
}
};
我在try {}和两个变量(电子邮件地址/密码)中都使用console.log,在两种情况下都到达了那里,并且在浏览器中没有出现错误。.我认为问题出在
const response = await axios.post("api/auth/login", { email: this.state.email, password: this.state.password });
localStorage.setItem("token", response.data.token);
getUsers vue:
methods: {
async getUsers() {
const response = await axios.get("api/alunos", {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
});
console.log(response);
},
getUsers反应:
componentDidMount() {
this.getUsers()
}
getUsers = async () => {
const response = await axios.get("api/alunos", {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
});
console.log(response);
};