首先我們先創建axios實例
const service = axios.create({ baseURL: url, //是用於請求的服務器 URL timeout: 5000, // 請求超時時間 如果請求話費了超過 `timeout` 的時間,請求將被中斷 headers: {'X-Custom-Header': 'foobar'} // 自定義請求頭 });
其他屬性參考:https://www.kancloud.cn/yunye/axios/234845
接下來我們來添加攔截器
// 添加請求攔截器
service .interceptors.request.use(function (config) { // 在發送請求之前做些什么
// 列如
config.headers['usertoken'] = token;
return config; }, function (error) { // 對請求錯誤做些什么 return Promise.reject(error); }); // 添加響應攔截器
service .interceptors.response.use(function (response) { // 對響應數據做點什么 return response; }, function (error) { // 對響應錯誤做點什么 return Promise.reject(error); });
假設你想移除攔截器
var myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor);