前言
axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,本质上也是对原生XHR的封装,只不过它是Promise的实现版本,符合最新的ES规范,在项目的实际开发中用到也比较多,这里我介绍一下实际开发中的基本配置
1.axios在项目中的安装
npm i axios --save 或 cnpm i axios --save
1.创建文件
步骤 1.在src文件夹下创建一个utils(名字随便)文件夹
2.在 utils文件夹下创建一个request.js(名字随便)文件
2. 引入与封装,代码如下
//request.js
import axios from 'axios' //引入 axios
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '../router'
import { getToken } from '@/utils/auth' //token的存储文件
import Vue from 'vue'
const _this = Vue.prototype
// 创建axios实例
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, ///直接使用.env.development中配置的地址
// withCredentials: true, // 跨域的时候发送cookie
timeout: 20000 // 设置超时时间,超时断开请求
})
//请求拦截器
service.interceptors.request.use(
config => {
if (store.getters.token) { //如果token纯在
//config.headers['Authorization'] = 'Bearer ' + getToken() //token放到请求头中
//获取当前时间戳
var t = new Date().getTime();
config.headers['timestamp'] = t; //让每个请求都携带当前的时间戳
config.headers['nonce'] = md5(t + getToken()); //让每个请求都携带随机的加密串
config.headers['token'] = getToken() //让每个请求携带自定义token 请根据实际情况自行修改
}
config.headers['Content-Type'] = 'application/json'
return config
},
error => {
console.log(error)
return Promise.reject(error)
}
)
// 响应拦截器
service.interceptors.response.use(
response => {
const res = response.data
if (res.code !== 200) {
//
if (res.code === 401) { //token失效
MessageBox.confirm('您的身份证令牌已过期,您可以选择继续留在页面或者重新登录!', {
confirmButtonText: '重新登录',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// 退出到登录页
router.push('/login')
}).catch(err => {
})
} else {
_this.$msg.error(res.message) //如果接口报错了提示接口的错误
}
return Promise.reject(new Error(res.message || 'Error'))
} else {
if (response.config.method !== 'get') { _this.$msg.success(res.message) } //接口操作成功 只有不是get请求 的时候推出提示消息,(一般都是post,增,修,删需要提示下)
// 注意_this.$msg是我自己封装的提示消息的方法,你们用不了,可以用UI框架上的,很简单自行解决,。
return res
}
},
error => {
_this.$msg.error(res.message)
return Promise.reject(error)
}
)
export default service //暴露封装好的axios
3.挂载
//main.js
import $axios from '@/utils/request' //把封装好的axios引入
const _this = Vue.prototype
_this.$axios = $axios //挂载到vue实例
4.使用
getRes() {
let url = `test/index/indexChartData?`//请求地址
this.$axios.get(url).then(res=>{
if(res.code!==200) return;
// ...逻辑
}).catch(err=>{
}).finally(()=>{
})
}