1、在我的项目中装置 axios
vue add axios
2、main.js
import './plugins/axios' // 装置 axios 结束主动新增此行
3、./plugins/axios.js
import axios from 'axios'
import qs from 'qs'
import {ElMessage} from 'element-plus';
const http = {}
const Axios = axios.create({
timeout: 200000,
withCredentials: true, // 主动携带 cookie
baseURL: '', // 接口地址
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
validateStatus(status) {return status >= 200 && status < 300}
});
// 申请拦挡
Axios.interceptors.request.use(config => {
// 头部如需带上 token, 在此处配置
return config
}, err => {return Promise.reject(err)
})
// 响应拦挡
Axios.interceptors.response.use(res => {return res;}, err => {switch (err.response.status) {
case 400:
ElMessage({
showClose: true,
message: '申请出错', // 此处能够换成接口返回的报错信息
type: 'error'
});
break;
case 401:
ElMessage({
showClose: true,
message: '受权失败,请从新登录', // 此处能够换成接口返回的报错信息
type: 'error'
});
return;
case 422:
ElMessage({
showClose: true,
message: '参数谬误,请查看填写的参数', // 此处能够换成接口返回的报错信息
type: 'error'
});
return;
case 403:
ElMessage({
showClose: true,
message: '回绝拜访', // 此处能够换成接口返回的报错信息
type: 'error'
});
break;
case 404:
ElMessage({
showClose: true,
message: '申请谬误, 未找到该资源', // 此处能够换成接口返回的报错信息
type: 'error'
});
break;
case 500:
ElMessage({
showClose: true,
message: '请从新登录', // 此处能够换成接口返回的报错信息
type: 'error'
});
break;
}
return Promise.reject(err);
})
http.get = function(url, data = {}) {return new Promise((resolve, reject) => {
Axios.get(url, {params: data}).then(res => {resolve(res);
}).catch(err => {reject(err);
})
})
}
http.del = function(url, data = {}) {return new Promise((resolve, reject) => {
Axios.delete(url, {params: data}).then(res => {resolve(res);
}).catch(err => {reject(err);
})
})
}
http.post = function(url, data) {return new Promise((resolve, reject) => {Axios.post(url, qs.stringify(data)).then(res => {resolve(res);
}).catch(err => {reject(err);
})
})
}
export default http
4、封装申请接口
url.js:申请的门路
index.js: 封装的接口办法
url.js
const url = {
'Login': '/login',
'Test': '/test',
}
module.exports = url;
index.js
import axios from '@/plugins/axios'
import url from './url.js'
let API = {};
// 登录
API.login = function(data) {return axios.post(url.Login, data);
}
// 获取测试内容
API.getTest= function() {return axios.get(url.Test);
}
export default API
5、调用接口
import API from '@/api/index.js'
export default {
name: 'login',
data() {
return {
adminForm: {
username: '',
password: ''
},
}
},
methods: {submitForm() {
let self = this;
API.login(self.adminForm).then(res => {console.log(res)
})
}
}
}