axios特点
1.从浏览器中创建 XMLHttpRequests
2.从 node.js 创建 http 请求
3.支持 Promise API
4.拦截请求和响应 (就是有interceptor)
5.转换请求数据和响应数据
6.取消请求
7.自动转换 JSON 数据
8.客户端支持防御 XSRF
npm i axios–save
npm i qs --save
npm i element-ui --save
npm i lodash --save
1.在入口文件中引入所需插件
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import url from './apiUrl'
import api from './apiUtil'
Vue.prototype.$axios = api.generateApiMap(url);
Vue.config.productionTip = false
Vue.use(ElementUI);
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
2.新建一个util文件夹(只要存放工具类)
在util中建apiUtil.js , apiUrl.js两个文件
apiUtil.js 封装请求体
import axios from 'axios'
import _ from 'lodash'
import router from '@/util/baseRouter.js'
import { Message } from 'element-ui'
import qs from 'qs'
const generateApiMap = (map) => {
let facade = {}
_.forEach(map, function (value, key) {
facade[key] = toMethod(value)
})
return facade
}
//整合配置
const toMethod = (options) => {
options.method = options.method || 'post'
return (params, config = {}) => {
return sendApiInstance(options.method, options.url, params, config)
}
}
// 创建axios实例
const createApiInstance = (config = {}) => {
const _config = {
withCredentials: false, // 跨域是否
baseURL: '',
validateStatus: function (status) {
if(status != 200){
Message(status+':后台服务异常')
}
return status;
}
}
config = _.merge(_config, config)
return axios.create(config)
}
//入参前后去空格
const trim = (param) =>{
for(let a in param){
if(typeof param[a] == "string"){
param[a] = param[a].trim();
}else{
param = trim(param[a])
}
}
return param
}
//restful路径参数替换
const toRest = (url,params) => {
let paramArr = url.match(/(?<=\{).*?(?=\})/gi)
paramArr.forEach(el=>{
url = url.replace('{'+el+'}',params[el])
})
return url
}
//封装请求体
const sendApiInstance = (method, url, params, config = {}) => {
params = trim(params)
if(!url){
return
}
let instance = createApiInstance(config)
//响应拦截
instance.interceptors.response.use(response => {
let data = response.data //服务端返回数据
let code = data.meta.respcode //返回信息状态码
let message = data.meta.respdesc //返回信息描述
if(data === undefined || typeof data != "object"){
Message('后台对应服务异常');
return false;
}else if(code != 0){
Message(message);
return false;
}else{
return data.data;
}
},
error => {
return Promise.reject(error).catch(res => {
console.log(res)
})
}
)
//请求方式判断
let _method = '';
let _params = {}
let _url = ''
if(method === 'form'){
_method = 'post'
config.headers = {'Content-Type':'application/x-www-form-urlencoded'}
_params = qs.stringify(params)
_url = url
}else if(method === 'resetful'){
_method = 'get'
_params = {}
_url = toRest(url,params)
}else if(method === 'get'){
_method = 'get'
_params = {
params: params
}
_url = url
}else if(method === 'post'){
_method = 'post'
_params = params
_url = url
}else{
Message('请求方式不存在')
}
return instance[_method](_url, _params, config)
}
export default {
generateApiMap : generateApiMap
}
apiUrl.js 配置所有请求路径参数
其中resetful风格请求的路径中的请求字段必须写在 ‘{}’中
const host= '/api' //反向代理
export default {
userAdd:{ url: host + "/user/add", method:"post" },
userList:{ url: host + "/user/userList", method:"get" },
userInfo:{ url: host + "/user/userInfo/{id}/{name}", method:"resetful"},
userInsert:{ url: host + "/login", method:"form"},
}
四种请求方式的入参统一都以object形式传入
APP.vue
<template>
<div class="login">
<el-button type="primary" @click="submitForm" class="submit_btn">登录</el-button>
</div>
</template>
<script>
export default {
data() {
return {
};
},
methods:{
submitForm(){
this.$axios.userAdd({
id:'123',
name:'liyang'
}).then(data=>{
console.log(data)
})
}
}
};
</script>
ps:入参也可以再请求interceptors.request中封装
vue项目封装axios:https://blog.csdn.net/zhanglong_web/article/details/78786940
如有疑问,欢迎批评指正~~~~