Vue-cli 請求代理配置,封裝 Axios 及請求攔截器和響應攔截器

Vue-cli 請求代理配置及封裝 Axios

大佬止步,小白往下。

HTTP 請求代理配置

vue-cli 2.x

// /config/index.js
proxyTable: {
  '/api-1': {
    target: 'http://xxx.xxx.xxx.xxx:8080',
    changeOrigin: true,
    pathRewrite: {
      // 以 /api-1 開頭的請求路徑都會被 'http://xxx.xxx.xxx.xxx:8080' 代理
      '^/api-1': '' 
    }
  },
  '/api-2': {
    target: 'http://xxx.xxx.xxx.xxx:8081',
    changeOrigin: true,
    pathRewrite: {
      // 以 /api-2 開頭的請求路徑都會被 'http://xxx.xxx.xxx.xxx:8081' 代理
      '^/api-2': ''
    }
  }
}

vue-cli 3.x

// vue.config.js(該文件在項目的根目錄下,默認沒有這個文件,用時需要自己新建)
module.exports = {
  devServer: {
    proxy: {
      '/api-1': {
        target: 'http://xxx.xxx.xxx.xxx:8080',
        ws: true, // 是否開啓 websokets
        secure: false, // 是否安全,https 爲 true,http 爲 false
        changeOrigin: true,
        pathRewrite: {
          '^/api-1': ''
        }
      },
      '/api-2': {
        target: 'http://xxx.xxx.xxx.xxx:8081',
        ws: true,
        secure: false,
        changeOrigin: true,
        pathRewrite: {
          '^/api-2': ''
        }
      }
    }
  }
};

調用

axios({
  // xxxx/xxxx 爲代理配置的 target 後的路徑 
  url: '/api-1/xxxx/xxxx',
  ...
});

Axios 封裝

封裝請求共用函數

變換較大的、常用的參數放前面,不常改變的參數和有默認值的參數放在參數隊列最後。

// /src/api/ajax.js (該目錄及名稱可自定義)
import axios from 'axios'
const request = axios.create({
  // 生產環境和開發環境的請求域名和端口
  baseURL: process.env.NODE_ENV === 'production' ? 'http://192.168.0.247:92/' : '',
  withCredentials: false
});
request.interceptors.request.use(config => {
  // 請求攔截器,可在此做請求之前的處理,比如綁定 token,存儲或清除某些數據等
  return config;
});
request.interceptors.response.use(res => {
  // 響應攔截器,可在此處做統一的請求失敗處理等操作
  console.log(res);
});
export default function ajax(
  url,
  params = {},
  type = 'post',
  errorCallBack,
  header = {headers: {'Content-Type': 'application/json'}}
) {
  return new Promise(resolve => {
    request[type](url, type === 'get' ? {params} : params, header)
      .then(res => resolve(res.data))
      .catch(e => {
        errorCallBack && errorCallBack();
        console.log(e);
      });
  });
}

封裝項目中的請求列表列表

// /src/api/index.js (該目錄及名稱可自定義)
import ajax from "./ajax";
const API1 = '/api-1';
const API2 = '/api-2';

// params 是個對象,存放請求所有參數列表
const req1 = params => ajax(API1 + '/xxx/xxx/xxx', params);
const req2 = params => ajax(API2 + '/xxx/xxx/xxx', params);

export default {
  req1,
  req2
}

在 main.js 配置

// main.js
...
import $http from './api'
Vue.prototype.$http = $http;
...

在任意組件中的調用

export default {
  name: 'xxx',
  methods: {
    async req() {
      // res爲請求返回值,如果要傳其他值,看上面封裝的 ajax 函數的參數列表 
      const res = await this.$http.req1({
        ... // 參數列表
      });
    }
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章