[英]How to get data in the axios header to a component in Vue
我有一个 axios apiClient
,我正在尝试将存储在localStorage
中的 email 放入 header 中。 在我的组件中,我尝试使用
response.headers['email']
并将其分配给 email 变量,但我没有定义。 我在localStorage
中获取 email 但无法在组件中获取它。 任何帮助将不胜感激。
Axios
const apiClient = axios.create({
baseURL: `${API}`,
withCredentials: false,
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
});
apiClient.interceptors.request.use(function (config) {
let token = JSON.parse(localStorage.getItem('token'));
let email = JSON.parse(localStorage.getItem('email'));
if (token) {
config.headers.Authorization = `Bearer ${token}`;
config.headers.email = `${email}`;
}
return config;
}, function (err) {
return Promise.reject(err);
});
这是我的组件中需要 email 数据的方法
methods: {
getOrders(){
service.getAllOrders()
.then(response => {
this.email = response.headers['email'];
console.log("email:", this.email)
})
}
}
getAllOrders()
执行 axios get
。
您设置了请求拦截器,但您正在检查响应header,这是两个不同的对象。 响应来自服务器,不受请求拦截器的影响。
您可以为响应创建不同的拦截器:
apiClient.interceptors.response.use((response) => {
response.headers.email = JSON.parse(localStorage.getItem('email'));
return response;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.