一般项目往往要对 axios 库进行二次封装,添加一些自定义配置和拦截器等
案例
./service/axios.js
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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
import axios from 'axios' import api from 'service/apiConfig' import store from 'vuexStore/store.js' import qs from 'qs' import template from 'url-template'
axios.defaults.timeout = 5000; axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8'
axios.interceptors.request.use( config => { if (localStorage.aynUserToken) { config.headers.common['X-AIYANGNIU-SIGNATURE'] = localStorage.aynUserToken; } return config; }, err => { return Promise.reject(err); } );
axios.interceptors.response.use( response => { if (response.data) { let code = response.data.code switch (code) { case 109: localStorage.aynUserToken = '' break; case 110: break; } } return response; }, error => { if (error.response) { let status = error.response.status switch (status) { case 401: localStorage.aynUserToken = '' break; } } let err = error.response ? (error.response.data || error.response) : (error.message || error) return Promise.reject(err) } );
export default async(type, apiName, url, data, options) => {
let vm = this let path = (apiName != '') ? api[apiName] + url : url let UrlTemplate = template.parse(path) if (data && data.hasOwnProperty("params")) { path = UrlTemplate.expand(data.params) if (!data.params) { data.params = {} } data.params._t = Date.now().toString() } else { path = UrlTemplate.expand(data) if (data) { data._t = Date.now().toString() } }
if (options && options.form) { let opt = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } data = qs.stringify(data) options === {} ? options.headers = opt.headers : options = opt } await axios[type](path, data, options).then((res) => { vm.result = res.data }) return vm.result }
|
调用
1 2 3 4 5 6 7 8 9 10 11 12 13
|
import res from 'service/axios'
export const AddToCart = (params) => res('post', 'apiItem', '/carts/add', params, {form:true})
export const GetCartList = () => res('get', 'apiItem', '/carts/list', {})
export const CartUpdate = (params) => res('put','apiItem', '/carts/update/{id}',params, {form:true})
export const CartDelete = (params) => res('delete','apiItem', '/carts/delete',{params}) ...
|
补充
url-template 库使用
1 2 3 4 5 6 7 8 9 10
|
var template = require('url-template');
var emailUrl = template.parse('/{email}/{folder}/{id}');
emailUrl.expand({ email: 'user@domain', folder: 'test', id: 42 });
|
axios 二次封装