Vue Quasar调用API出现“Authentication credentials were not provided”错误如何解决
问题排查与解决方案
- 问题根因:报错
detail: "Authentication credentials were not provided."翻译为未提供身份认证凭证,说明你的请求没有携带后端要求的身份校验信息,后端无法识别访问身份直接拦截了请求。 - 排查1:检查axios全局是否配置了请求拦截器携带认证头
大部分后端采用JWT认证机制,需要在请求头中携带登录后获取的token,你需要在Quasar的axios boot文件(通常为boot/axios.js)中添加全局拦截逻辑,示例代码:import axios from 'axios' export default ({ Vue, router }) => { // 全局配置请求拦截器 axios.interceptors.request.use( (config) => { // 从本地存储读取登录时保存的访问令牌 const accessToken = window.localStorage.getItem('access_token') if (accessToken) { // 给所有请求添加认证头 config.headers.Authorization = `Bearer ${accessToken}` } return config }, (error) => Promise.reject(error) ) Vue.prototype.$axios = axios } - 排查2:确认登录逻辑是否正确存储令牌
登录接口调用成功后,需要把后端返回的access_token正确存入localStorage或者sessionStorage,如果没有存储令牌,拦截器无法读取,请求还是不会携带认证信息。 - 排查3:适配后端其他认证规则
如果后端采用Session+Cookie认证方案,需要额外开启axios跨域携带Cookie的配置,添加到axios配置中:axios.defaults.withCredentials = true - 临时验证方法
你可以先在当前请求手动加认证头测试,确认是不是认证信息的问题:// 把下面的测试token替换成你登录后拿到的真实token await this.$axios.get(this.$serverUrls.showStudent, { headers: { Authorization: 'Bearer 你的真实访问令牌' } }) - 额外优化建议
你当前的错误捕获逻辑没有适配401认证失败的场景,可以补充判断,用户登录过期后自动跳转到登录页:catch ((error) => { if (error.response.status == 400) { this.$q.notify({ color: "negative", position: "top", message: "شماره تکراری است", icon: "report_problem", }); } else if (error.response.status == 401) { // 清除无效令牌 localStorage.removeItem('access_token') // 跳转到登录页,根据你的实际路由调整 this.$router.push('/login') this.$q.notify({ color: "negative", position: "top", message: "登录已过期,请重新登录", icon: "report_problem", }); } else { this.$q.notify({ color: "negative", position: "top", message: "مشکل در اتصال", icon: "report_problem", }); } })
内容的提问来源于stack exchange,提问作者rozhan
相关产品推荐
相关产品推荐

