Vue 中 axios 攔截器的封裝

2019-12-4    seo達(dá)人

在vue項(xiàng)目中,和后臺交互獲取數(shù)據(jù)這塊,我們通常使用的是axios庫,它是基于promise的http庫,可運(yùn)行在瀏覽器端和node.js中。他有很多優(yōu)秀的特性,例如攔截請求和響應(yīng)、取消請求、轉(zhuǎn)換json、客戶端防御cSRF等。

一 . 安裝



npm install axios;

1

二 . 引入

在項(xiàng)目的src目錄中,新建一個(gè)request文件夾,然后在里面新建一個(gè)http.js和一個(gè)api.js文件。http.js文件用來封裝我們的axios,api.js用來統(tǒng)一管理我們的接口。

三 . 開始封裝



在http.js中引入axios . vue及其他

import Axios from 'axios'; // 引入axios

import { Message, Loading, Notification } from 'element-ui'

import vue from 'vue';

1

2

3

http.js文件全部代碼如下:



import Axios from 'axios';

import store from '../store';

import { Message, Loading, Notification } from 'element-ui'

import vue from 'vue';

// 環(huán)境的切換

if (process.env.NODE_ENV == 'development') {

  Axios.defaults.baseURL = "http://10.230.39.58:33390/devops";

}

else if (process.env.NODE_ENV == 'production') {

  Axios.defaults.baseURL = "http://10.230.39.58:33390/devops";

}

// request請求攔截器

Axios.defaults.withCredentials = true

vue.prototype.$axios = Axios

//請求超時(shí)時(shí)間

// Axios.defaults.timeout = 100000;

Axios.defaults.headers.get['Content-Type'] = "application/json"

Axios.interceptors.request.use(config => {

  const Basic = sessionStorage.getItem("basicParam")

  if (Basic) {

    config.headers.Authorization = Basic ${Basic};

  } else {

    console.log("無校驗(yàn)值");

  }

  return config;

}, error => {

  Promise.reject(error);

})

// respone返回?cái)r截器

Axios.interceptors.response.use(

  response => {

    if (response.data.code !== 200) {

      Notification.error({

        title: '錯(cuò)誤',

        message: response.data.message

      });

    }

    return response.data;

  }, error => {

    // Notification.error({

    //   title: '錯(cuò)誤',

    //   message: '系統(tǒng)異常'

    // });

    console.log('err' + error);// for debug

    return Promise.reject(error);

  }

)



export default Axios;



1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

api.js文件全部代碼如下:



import axios from 'axios';

/

  封裝get方法

 
@param url

  @param data

 
@returns {Promise}

 */



export function fetch(url, params = {}) {

  return new Promise((resolve, reject) => {

    axios.get(url, {

      params: params

    })

      .then(response => {

        resolve(response.data);

      })

      .catch(err => {

        reject(err)

      })

  })

}





/*

 
封裝post請求

  @param url

 
@param data

  @returns {Promise}

 
/



export function _post(url, data = {}) {

  return new Promise((resolve, reject) => {

    axios.post(url, data)

      .then(response => {

        console.log(response,

          "response");



        resolve(response);

      }, err => {

        reject(err)

      })

  })

}



/

  • 封裝patch請求
  • @param url
  • @param data
  • @returns {Promise}

    */



    export function patch(url, data = {}) {

      return new Promise((resolve, reject) => {

        axios.patch(url, data)

          .then(response => {

            resolve(response.data);

          }, err => {

            reject(err)

          })

      })

    }



    /**
  • 封裝put請求
  • @param url
  • @param data
  • @returns {Promise}

    */



    export function put(url, data = {}) {

      return new Promise((resolve, reject) => {

        axios.put(url, data)

          .then(response => {

            resolve(response.data);

          }, err => {

            reject(err)

          })

      })

    }



    在main.js中引入api.js



    import { _post, fetch, patch, put } from './utils/api'

    //定義全局變量

    Vue.prototype.$post = post;

    Vue.prototype.$fetch = fetch;

    Vue.prototype.$patch = patch;

    Vue.prototype.$put = put;

    1

    2

    3

    4

    5

    6

    最后在組件里直接使用



     this.$post('/api/v2/movie/top250')

          .then((response) => {

            console.log(response)

          })

          



    其他方法用法相同




分享本文至:

日歷

鏈接

個(gè)人資料

存檔