axios設置請求攔截和響應攔截


首先我們先創建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);

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM