javascript - Axios:用户在登录前尝试
问题描述
当我使用正确的电子邮件/密码发送“EnvioLogin”时,我从“/login”获得访问令牌,但之后我无法获得“/users”当我在浏览器中检查时,我得到这个:https://imgur。 com/NZFXeiJ https://imgur.com/B2DCebE
用户尝试登录后如何运行创建的挂钩?
import axios from "axios";
export default {
name: "login",
data() {
return {
showError: false,
email: "",
password: "",
};
},
async created() {
const response = await axios.get("api/users", {
headers: {
Authorization: "Bearer " + localStorage.getItem("token")
}
});
console.log(response);
},
methods: {
async EnvioLogin() {
try {
const response = await axios.post("api/auth/login", {
email: this.email,
password: this.password,
});
localStorage.setItem("token", response.data.token);
const status = JSON.parse(response.status);
if (status == "200") {
console.log(response);
this.$router.push("intermediorotas");
this.showLogin = false;
}
} catch (error) {
this.showError = true;
setTimeout(() => {
this.showError = false;
}, 2000);
}
},
},
解决方案
创建的钩子中的代码可以在名为的单独方法中,getUsers
然后在方法中调用它EnvioLogin
:
import axios from "axios";
export default {
name: "login",
data() {
return {
showError: false,
email: "",
password: "",
};
},
created() {
this.getUsers();
},
methods: {
async getUsers(){
const response = await axios.get("api/users", {
headers: {
Authorization: "Bearer " + localStorage.getItem("token")
}
});
console.log(response);
},
async EnvioLogin() {
try {
const response = await axios.post("api/auth/login", {
email: this.email,
password: this.password,
});
localStorage.setItem("token", response.data.token);
const status = JSON.parse(response.status);
if (status == "200") {
this.getUsers();
console.log(response);
this.$router.push("intermediorotas");
this.showLogin = false;
}
} catch (error) {
this.showError = true;
setTimeout(() => {
this.showError = false;
}, 2000);
}
},
},
推荐阅读
- asp.net-core - 尽管配置遵循文档,为什么 CORS 会阻止我在 Bolero (F# Blazor) 中的获取?
- angular - 其他函数中元素的角度刷新 validateFn
- python - 需要帮助使所得税计算器的代码在 Python 上更高效
- python - 如何使用 buildpack 构建非 web python 应用程序映像?
- c# - 数据列表项命令功能不起作用
- firebase - 没有为“FirebaseStorage”类型定义方法“getReferenceFromUrl”
- r - R中平方根的Newton-Raphson方法
- excel - 表格过滤器宏
- laravel - 如何在 laravel 6.* 或更高版本中使用 3/4 用户名?
- sql - $exception 无法计算表达式。不支持操作。未知错误:0x80040914