[英]How can I automatically get Bearer token to axios header in view using vue and laravel
I am trying to get the token of current user to get retrieve the data like this:我正在尝试获取当前用户的令牌来检索这样的数据:
async getUser() {
const config = {
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ...'
}
}
await this.axios
.get("/api/auth/testapi", config)
.then((response) => {
this.user = response.data;
})
.catch((error) => {
console.log(error);
this.user = [];
});
},
How can I set the 'Authorization' header to auto get the current token of the authenticated user?如何设置“授权”标头以自动获取经过身份验证的用户的当前令牌?
I tried local storage as showing below:我尝试了本地存储,如下所示:
async getUser() {
const token = localStorage.getItem('access_token');
const config = {
headers: {
'Accept': 'application/json',
'Authorization': `Bearer ${token}`
}
}
await this.axios
.get("/api/auth/testapi", config)
.then((response) => {
this.user = response.data;
})
.catch((error) => {
console.log(error);
this.user = [];
});
},
and it didn't work as well.它也没有用。
What seems to be the problem?似乎是什么问题?
UPDATE:更新:
app.js:应用程序.js:
require("./src/main.js");
import VueAxios from "vue-axios";
import axios from "axios";
Vue.use(VueAxios, axios);
if (localStorage.has("access_token")) {
axios.defaults.headers.common["Authorization"] =
"Bearer " + localStorage.getItem("access_token");
}
loginSuccess(accessToken) {
localStorage.setItem('access_token', accessToken);
window.location.href = '/home';
}
There is a problem after "if" ends “if”结束后出现问题
';' expected.
What i would do,我会做什么,
on every request, on a js file (not vue), like your bootstrap.js file (because it will be loader sooner):在每个请求上,在 js 文件(不是 vue)上,比如你的 bootstrap.js 文件(因为它会更快加载):
let access_token = localStorage.getItem('access_token');
if(access_token) {
axios.defaults.headers.common['Authorization'] = 'Bearer ' + access_token;
}
on your login function, when you login the user and retrieve the access token:在您的登录功能上,当您登录用户并检索访问令牌时:
loginSuccess(accessToken) {
localStorage.setItem('access_token', accessToken);
window.location.href = '/home';
}
it will redirect the user to your home page or whatever page the user needs to be redirected to, and the access_token will be set on the localStorage.它会将用户重定向到您的主页或用户需要重定向到的任何页面,并且 access_token 将在 localStorage 上设置。
The last bit remaining is deleting the localStorage access_token
item when the user is logged out, and perhaps catching 401 with an interceptor, to delete access_token and redirect to /login on token expiration.剩下的最后一点是在用户注销时删除 localStorage
access_token
项,并可能使用拦截器捕获 401,以删除 access_token 并在令牌过期时重定向到 /login。
window.axios.interceptors.response.use(function (response) {
return response;
}, function (error) {
if (401 === error.response.status) {
localStorage.removeItem('access_token');
window.location.href = '/login'
} else {
return Promise.reject(error);
}
});
You perhaps will need to check the domain of the 401 to be sure it's yours, if you intent to make axios requests to external endpoints that are not yours如果您打算向不属于您的外部端点发出 axios 请求,您可能需要检查 401 的域以确保它是您的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.