问题描述
是否可以在axios.all方法中附加标头,还是必须将标头分别附加到每个请求。
axios.all([
axios.delete('http://localhost:5000/requests/'+{id}),axios.post('http://localhost:5000/records/'+{id,response}),],{
headers: {Authorization: localStorage.getItem('auth-token')}
}).then(res => console.log(res.data))
.catch(err => console.log(err));
解决方法
您可以为给定的所有请求设置默认标头
axios.defaults.headers.common['Authorization'] = token;
设置此选项后,默认情况下,所有后续网络调用都将带有Authorization
头。此解决方法将帮助您提供应用程序全局标头,例如Authorization
标头。您可以创建单独的Axios实例为
const axiosInstance axios.create({
headers: {Authorization: token}
});
您可以选择一种解决方法。
,创建一个axios
实例,并对所有请求使用相同的实例(推荐)
const axiosInstance = axios.create({
headers: {'X-Custom-Header': 'foobar'}
});
示例:
const axiosInstance = axios.create({
headers: {
Authorization: localStorage.getItem('auth-token')
}
});
axios.all([
axiosInstance.delete("http://localhost:5000/requests/" + {id}),axiosInstance.post("http://localhost:5000/records/" + {id,response})
]).then((res) => {
console.log("Response: ",res);
}).catch((error) => {
console.log("Error: ",error);
})