溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

vue中怎么利用axios實(shí)現(xiàn)一個(gè)登錄請(qǐng)求攔截器

發(fā)布時(shí)間:2021-07-09 15:01:27 來(lái)源:億速云 閱讀:204 作者:Leah 欄目:web開發(fā)

vue中怎么利用axios實(shí)現(xiàn)一個(gè)登錄請(qǐng)求攔截器,相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。

1.安裝配置axios

cnpm install --save axios 

我們可以建一個(gè)js文件來(lái)做這個(gè)統(tǒng)一的處理,新建一個(gè)axios.js,如下

import axios from 'axios' 
import { Indicator } from 'mint-ui'; 
import { Toast } from 'mint-ui'; 
// http request 攔截器 
axios.interceptors.request.use( 
  config => { 
    Indicator.open() 
    return config; 
  }, 
  err => { 
    Indicator.close() 
    return Promise.reject(err); 
  }); 
// http response 攔截器 
axios.interceptors.response.use( 
  response => { 
    Indicator.close() 
    return response; 
  }, 
  error => { 
    Indicator.close() 
  }); 
export default axios

然后在main.js中引入這個(gè)js文件

import axios from './axio'; 
Vue.prototype.$axios = axios;

這樣就可以使用axios去請(qǐng)求了,在組件中可以用this.axios去調(diào)用

this.$axios({ 
    url:requestUrl+'homePage/v1/indexNewPropertiesResult', 
    method:'POST', 
   }).then(function(response){ //接口返回?cái)?shù)據(jù) 
    console.log(response) 
    that.modulesArr=response.data.data.modules; 
//   that.getRecommendGoods(0); 
   });

只有用axios請(qǐng)求接口,才能去攔截,現(xiàn)在已經(jīng)能在axios.js中攔截到了,可以在兩個(gè)狀態(tài)中做你需要的操作

補(bǔ)充:

axios使用攔截器統(tǒng)一處理所有的http請(qǐng)求

axios使用攔截器

在請(qǐng)求或響應(yīng)被 then 或 catch 處理前攔截它們。

?http request攔截器

// 添加請(qǐng)求攔截器
axios.interceptors.request.use(function (config) {
  // 在發(fā)送請(qǐng)求之前做些什么
  return config;
 }, function (error) {
  // 對(duì)請(qǐng)求錯(cuò)誤做些什么
  return Promise.reject(error);
 });

?http respones攔截器

// 添加響應(yīng)攔截器
axios.interceptors.response.use(function (response) {
  // 對(duì)響應(yīng)數(shù)據(jù)做點(diǎn)什么
  return response;
 }, function (error) {
  // 對(duì)響應(yīng)錯(cuò)誤做點(diǎn)什么
  return Promise.reject(error);
 });

?移除攔截器

var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

?為自定義axios實(shí)例添加攔截器

var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

看完上述內(nèi)容,你們掌握vue中怎么利用axios實(shí)現(xiàn)一個(gè)登錄請(qǐng)求攔截器的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI