我正在尝试获取当前用户的令牌来检索数据,如下所示:
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 = [];
});
},
如何设置“授权”标头以自动获取经过身份验证的用户的当前令牌?
我尝试了本地存储,如下所示:
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 = [];
});
},
但效果并不好。
问题出在哪里?
更新:
app.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';
}
“if”结束后出现问题
';' expected.
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我会做什么,
在每个请求上,在 js 文件(不是 vue)上,例如 bootstrap.js 文件(因为它将更快加载):
let access_token = localStorage.getItem('access_token'); if(access_token) { axios.defaults.headers.common['Authorization'] = 'Bearer ' + access_token; }在您的登录功能上,当您登录用户并检索访问令牌时:
loginSuccess(accessToken) { localStorage.setItem('access_token', accessToken); window.location.href = '/home'; }它将用户重定向到您的主页或用户需要重定向到的任何页面,并且 access_token 将在 localStorage 上设置。
剩下的最后一点是在用户注销时删除 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); } });如果您打算向不属于您的外部端点发出 axios 请求,您可能需要检查 401 的域以确保它是您的域