axios是一個基於Promise(本機支持ES6 Promise實現) 的HTTP庫,用於瀏覽器和 nodejs 的 HTTP 客戶端。具備如下特徵:vue
npm install axios 進行安裝,安裝成功後 import axios from 'axios' 進行引入模塊,再對axios對象進行設置。如node
/** * 建立axios對象 **/ let axiosInstance =axios.create({ baseURL: configHttp.domain, withCredentials:true, });
備註:使用 Vue.prototype.$http = axios; 進行配置於vue項目中,在頁面中可以使用this.$http.get('xxxx').then().catch()。ios
數據請求的服務器URL,此配置必須存在,不然無訪問路徑沒法進行數據請求。web
建立請求時使用的方法,默認get方式。有多種請求方式,如:request/get/delete/head/post/put/patch,經常使用get與post.npm
設置一個統一的基礎路徑(如http://www.demo.com/api/),使axios的get或post中的url使用相對URL,更改訪問域名或端口號時只更改對應的baseURL值便可。json
headers是即將被髮送的自定義請求頭,可設置請求的數據標識(token)或post請求的數據類型等。axios
請求超時時間,單位爲毫秒,若超過超時時間則請求中斷。0表示無超時時間。api
跨域請求時是否須要使用憑證,默認爲false跨域
優先級別爲:自定義實例>全局默認值>自帶默認值promise
1.全局默認值
axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
2.自定義實例
// 建立實例時設置配置的默認值 var instance = axios.create({ baseURL: 'https://api.example.com' }); // 在實例已建立後修改默認值 instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
備註:也可在請求攔截中進行設置對應的配置。
在請求或響應被 then 或 catch 處理前攔截他們,分爲請求攔截器和響應攔截器;
示意圖:
通常在請求攔截器中增長標識token或其餘請求配置,在響應攔截器中對統一錯誤或狀態碼進行處理(跳轉統一頁面如登陸)
// 添加請求攔截器 axios.interceptors.request.use(function (config) { // 在發送請求以前作些什麼 return config; }, function (error) { // 對請求錯誤作些什麼 return Promise.reject(error); }); // 添加響應攔截器 axios.interceptors.response.use(function (response) { // 對響應數據作點什麼 return response; }, function (error) { // 對響應錯誤作點什麼 return Promise.reject(error); });
備註:在headers.post['Content-Type']不爲application/json時,傳遞post參數時需使用querystring中的querystring.stringify對參數進行格式化處理。
import axios from 'axios' import configHttp from '../../configHttp' /** * 建立axios對象 **/ let axiosInstance =axios.create({ baseURL: configHttp.domain, withCredentials:true, }); /** * 訪問請求攔截(在請求前處理) **/ axiosInstance.interceptors.request.use( function (config) { config.headers.common['Platform'] = 'web'; return config; }, function (error) { return Promise.reject(error) } ); /** * 響應請求攔截(在響應前處理) **/ axiosInstance.interceptors.response.use( function (response) { return response; }, function (error) { if(error.response){ let status=error.response.status; switch (status) { case 401: // 跳轉至login break; } } //處理報錯 記錄日誌 if (error !== undefined) { console.log(error); } } ); /** * http請求響應處理函數 **/ let httpResponseHandle = function(){ let self = this; let res = self.res; if (res.code == '0') { self.successCallback && self.successCallback(res); } else if (res.code == 'C00004' || res.code =='C00002') { // 清除token // 跳轉至login } else { // 統一錯誤彈出 self.failCallback && self.failCallback(res); } }; let http= { /** * 以get方式請求獲取JSON數據 * @param {Object} opts 配置項,能夠包含如下成員: * @param {String} opts.url 請求地址 * @param {Object} opts.params 附加的請求參數 * @param {Function} opts.successCallback 成功的回調函數 * @param {Function} opts.failCallback 失敗的回調函數 * **/ get: function (opts) { axiosInstance .get(opts.url, {params: opts.params}) .then(function (res) { opts.res = res.data; httpResponseHandle.call(opts); }) .catch(function (err) { if (err.response) { if (err.response.data) { opts.res = err.response.data; httpResponseHandle.call(opts); } else { // 統一錯誤彈出 } } }); }, /** * 以post方式請求獲取JSON數據 * @param {Object} opts 配置項,能夠包含如下成員: * @param {String} opts.url 請求地址 * @param {Object} opts.params 附加的請求參數 * @param {Function} opts.successCallback 成功的回調函數 * @param {Function} opts.failCallback 失敗的回調函數 * **/ post: function (opts) { axiosInstance .post(opts.url, opts.params) .then(function (res) { opts.res = res.data; httpResponseHandle.call(opts); }) .catch(function (err) { if (err.response) { if (err.response.data) { opts.res = err.response.data; httpResponseHandle.call(opts); } else { // 統一錯誤彈出 } } }); } }; export default http;
在Vue中使用prototype進行設置,不能使用use設置。
import http from '@/common/js/http.js';
Vue.prototype.$http = http;
import Vue from 'vue' import axios from '../common/js/http.js' Vue.prototype.$http = axios
vue單頁面中的methods中使用
this.$http.get({ url: 'comm/getDataInfo', params: { param1: xxx, param2: '3' }, successCallback: res => { // 數據處理 }, failCallback: res => {} });
this.$http.post({ url: 'common/userLogin', params: { username: 'admin', password: '123456' }, successCallback: res => { // 數據處理 }, failCallback: res => {} });