Vue 中使用 Axios 访问后端接口时,Authorization 参数丢失问题
在访问后端 security+oauth2 项目接口时,使用普通的 ajax 携带 token 可以正常访问接口,但在 Vue 中使用 axios 访问接口并携带 token,后端未接收到前端传递的 Authorization 参数,导致接口提示未登录,这是什么原因呢?
这个问题可能是由于 axios 发送请求时默认将请求头设置为'Content-Type: application/json',而不是'application/x-www-form-urlencoded',导致后端无法正确解析 token。
您可以尝试在 axios 的请求中手动设置请求头的'Content-Type' 为'application/x-www-form-urlencoded',并将 token 以'Authorization: Bearer token' 的格式放在请求头中。
以下是一个示例代码:
import axios from 'axios';
// 创建一个axios实例
const instance = axios.create({
baseURL: 'http://your-backend-api-url',
timeout: 5000,
});
// 在请求发送之前对请求进行处理
instance.interceptors.request.use(config => {
// 设置请求头的Content-Type为application/x-www-form-urlencoded
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
// 从localStorage中获取token
const token = localStorage.getItem('token');
// 如果存在token,则在请求头中添加Authorization字段
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
});
// 发送请求
instance.get('/api/your-api-endpoint')
.then(response => {
// 处理响应
console.log(response.data);
})
.catch(error => {
// 处理错误
console.log(error);
});
请确保您已经正确获取到了 token,并将其存储在合适的地方(比如 localStorage)供 axios 使用。如果问题仍然存在,请检查后端接口的配置是否正确,确保后端能够正确解析请求头中的 Authorization 字段。
原文地址: https://www.cveoy.top/t/topic/qjwM 著作权归作者所有。请勿转载和采集!