在初始化Vue应用后,定义axios.defaults.baseURL = baseUrl;
会立即发送奇怪的get请求。感谢您的帮助!
代码和网络请求的图片如下:
试图使用Setting baseUrl for Axios in Vue js sends out request
但这对我不起作用
import axios from 'axios';
export const baseUrl = 'http://imfood-core.local';
axios.defaults.baseURL = baseUrl;
axios.interceptors.request.use(function (request) {
if(request.url !== `/api/login_check`){
request.headers['Authorization'] = `Bearer ${localStorage.getItem('token')}`
}
return request;
}, function (error) {
return Promise.reject(error);
});
axios.interceptors.response.use(function (response) {
axios.defaults.baseURL = baseUrl;
return response;
}, function (error) {
if(error.response && error.response.status == 401 && error.config.url !== `${baseUrl}/api/login_check`){
localStorage.removeItem('token');
window.location.reload();
return Promise.reject(error);
}
return Promise.reject(error);
});
export default axios;
[1]: https://i.stack.imgur.com/6E9dD.png
[2]: https://i.stack.imgur.com/fnBST.png
[3]: https://i.stack.imgur.com/7sy5z.png
答案 0 :(得分:0)
您可以创建一个新的axios实例,然后将其提供给您的文件,只需导入该文件即可。
import axios from 'axios'
const client = axios.create({
baseURL: 'http://imfood-core.local'
})
client.interceptors.request.use(function (request) {
if(request.url !== `/api/login_check`){
request.headers['Authorization'] = `Bearer ${localStorage.getItem('token')}`
}
return request;
}, function (error) {
return Promise.reject(error);
});
...
export default client