1. 概述
1.1 簡介
axios是一個基於Promise(本機支持ES6 Promise實現) 的HTTP庫,用於瀏覽器和 nodejs 的 HTTP 客戶端。具有以下特征:
-
- 從瀏覽器中創建 XMLHttpRequests
- XMLHttpRequest對象用於在后台與服務器交換數據,可做到在不重新加載頁面的情況下更新網頁,在頁面已加載后從服務器請求數據或接收數據,在后台向服務器發送數據。所有的瀏覽器都支持XMLHttpRequest對象。
- 從 node.js 創建 http 請求
- 如get/post等
- 支持 Promise API
- 如promise所支持的鏈式回調,.then(res => {}).catch(err =>{})
- 攔截請求和響應
- 在請求之前或響應之后進行的處理,如請求之前增加統一的token標識,響應之后對公用的錯誤進行處理等。
- 轉換請求數據和響應數據
- 取消請求
- 自動轉換JSON數據
- 客戶端支持防御XSRF
- 從瀏覽器中創建 XMLHttpRequests
1.2 引入使用
npm install axios 進行安裝,安裝成功后 import axios from 'axios' 進行引入模塊,再對axios對象進行設置。如
/** * 創建axios對象 **/ let axiosInstance =axios.create({ baseURL: configHttp.domain, withCredentials:true, });
備注:使用 Vue.prototype.$http = axios; 進行配置於vue項目中,在頁面中可使用this.$http.get('xxxx').then().catch()。
1.3 常用請求配置
1.3.1 url
數據請求的服務器URL,此配置必須存在,否則無訪問路徑無法進行數據請求。
1.3.2 method
創建請求時使用的方法,默認get方式。有多種請求方式,如:request/get/delete/head/post/put/patch,常用get與post.
1.3.3 baseURL
設置一個統一的基礎路徑(如http://www.demo.com/api/),使axios的get或post中的url使用相對URL,更改訪問域名或端口號時只更改對應的baseURL值即可。
1.3.4 headers
headers是即將被發送的自定義請求頭,可設置請求的數據標識(token)或post請求的數據類型等。
1.3.5 timeout
請求超時時間,單位為毫秒,若超過超時時間則請求中斷。0表示無超時時間。
1.3.6 withCredentials
跨域請求時是否需要使用憑證,默認為false
1.4 配置的默認與自定義實例
優先級別為:自定義實例>全局默認值>自帶默認值
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;
備注:也可在請求攔截中進行設置對應的配置。
1.5 攔截器
在請求或響應被 then 或 catch 處理前攔截他們,分為請求攔截器和響應攔截器;
-
- 請求攔截器(interceptors.request)是指可以攔截每次或指定HTTP請求,並可修改配置項。
- 響應攔截器()可以攔截每次HTTP請求對應的響應,並可修改返回結果項。
示意圖:
一般在請求攔截器中增加標識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); });
2. 實例
2.1 axios配置
備注:在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;
2.2 實例調用
在Vue中使用prototype進行設置,不能使用use設置。
1.main.js中直接寫入
import http from '@/common/js/http.js';
Vue.prototype.$http = http;
2.其他引入
import Vue from 'vue' import axios from '../common/js/http.js' Vue.prototype.$http = axios
2.3 頁面使用
vue單頁面中的methods中使用
1.get示例
this.$http.get({ url: 'comm/getDataInfo', params: { param1: xxx, param2: '3' }, successCallback: res => { // 數據處理 }, failCallback: res => {} });
2.post示例
this.$http.post({ url: 'common/userLogin', params: { username: 'admin', password: '123456' }, successCallback: res => { // 數據處理 }, failCallback: res => {} });
2.4 http請求Content-Type: application/x-www-form-urlencoded
接口使用x-www-form-urlencoded格式接收/傳遞數據時,需要使用qs(原來的querystring)對所傳遞的參數進行格式化處理;
1.設置數據格式
headers: {
'Content-Type': 'application/x-www-form-urlencoded', }
2.在請求攔截處統一處理參數格式化
config.data = qs.stringify(config.data)
import axios from 'axios' import qs from 'qs' const http = axios.create({ timeout: 15000, headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }) /** * 請求攔截器 */ http.interceptors.request.use(config => { const objParams = { appKey: 'ccc', bizContent: JSON.stringify(config.data), } config.data = qs.stringify(objParams) // objParams為傳遞參數 return config }, error => { Promise.reject(error) })