1.axios安装:
npm install axios -D
2.封装axios,index.js
/** 接口调用工具*/
import axios from 'axios' 引用axios
// 配置API接口地址
var root = 'http://localhost:7002'
axios.defaults.headers.post['content-Type'] = 'application/json;charset=UTF-8';
// 自定义判断元素类型JS
function toType (obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
/** 参数过滤函数*/
function filterNull (o) {
for (var key in o) {
if (o[key] === null) {
delete o[key]
}
if (toType(o[key]) === 'string') {
o[key] = o[key].trim()
} else if (toType(o[key]) === 'object') {
o[key] = filterNull(o[key])
} else if (toType(o[key]) === 'array') {
o[key] = filterNull(o[key])
}
}
return o
}
/**添加headers,可以动态添加header参数*/
function setHeaders(headers){
axios.defaults.headers.school_id = headers.school_id;
axios.defaults.headers.token = headers.token;
}
//其实success与failure这两个参数,传过来的是两个放方法
function apiAxios (method, url,headers, params, success, failure) {
if (headers){
headers = filterNull(headers);
setHeaders(headers)
}
if (params) {
params = filterNull(params)
}
axios({
method: method,
url: url,
data: method === 'POST' || method === 'PUT' ? params : null,
params: method === 'GET' || method === 'DELETE' ? params : null,
baseURL: root,
withCredentials: false
})
.then(function (res) {
if (res.data.error_code === 1000) {
if (success) {
//使用success(data)方法
success(res.data)
}
} else {
failure(res.data)
}
})
.catch(function (err) {
let res = err.response
if (err) {
window.alert('api error, HTTP CODE: ' + res.status)
}
})
}
// 返回在vue模板中的调用接口
export default {
get: function (url,headers, params, success, failure) {
return apiAxios('GET', url,headers, params, success, failure)
},
post: function (url,headers, params, success, failure) {
return apiAxios('POST', url,headers, params, success, failure)
},
put: function (url,headers, params, success, failure) {
return apiAxios('PUT', url,headers, params, success, failure)
},
delete: function (url,headers, params, success, failure) {
return apiAxios('DELETE', url,headers, params, success, failure)
}
}
3.在main.js全局引用封装的axios js
import api from './api/index.js';
Vue.prototype.$api = api
4.使用例子,get请求与post请求
//get请求
this.$api.get(
'/devices', //url
{"school_id":schoolId,"token":null}, //headers
null, //params
successRes => { //success(data)方法
console.log(successRes)
},
failureRes =>{ //failure(data)方法
console.log(failureRes)
}
)
//post请求
this.$api.post(
'/device',
{"school_id":schoolId,"token":null},
{"name": "test","operator_name": "xichuan"},
successRes => {
console.log(successRes)
},
failureRes =>{
console.log(failureRes)
}
})
5.get请求可以用下面格式
//将上面的查分开来,这样更好理解,可以看出,最后两个参数其实传递的是两个方法,一个处理success,一个处理failure
var success = function myfun(res){
console.log(res)
}
var failure = function myfun(res){
console.log(res)
}
this.$api.get(
'/devices', //url
{"school_id":schoolId,"token":null}, //headers
null, //params
success(res), //success(data)方法
failure(res) //failure(data)方法
)
我不是大佬,我只是个勤劳的搬运工。看在如此辛苦的份上点个关注可好!
原文参考地址:https://blog.csdn.net/zc_ad/article/details/86520988