我在 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);
}
},
},
react不起作用:
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);
获取用户视图:
methods: {
async getUsers() {
const response = await axios.get("api/alunos", {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
});
console.log(response);
},
getUsers react:
componentDidMount() {
this.getUsers()
}
getUsers = async () => {
const response = await axios.get("api/alunos", {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
});
console.log(response);
};