前言:
接口拦截分为:
统一报错
未登录统一拦截
请求值,返回值统一处理
axios插件:
安装:
npm install axios
bower install axios #基本弃用
yarn add axios
CND静态引入:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
基本语法:
const axios = require('axios').default; #引入axios插件
GET请求示例代码:
const axios = require('axios');
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
// Optionally the request above could also be done as
axios.get('/user', {
params: { //GET请求固定格式 params:{xxx}
ID: 12345
}
})
.then(function (response) { #用于接收返回值,response后端返回
console.log(response);
})
.catch(function (error) { #捕获异常
console.log(error);
})
.then(function () {
// always executed
});
// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
try { #捕获异常
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) { #异常处理
console.error(error);
}
}
POST请求示例代码:
axios.post('/user', {
firstName: 'Fred', #跟get比较不需要params直接传参
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
发送多个请求:
Promise.all([getUserAccount(), getUserPermissions()]) //都哦个接口,号隔开
.then(function (results) {
const acct = results[0];
const perm = results[1];
});
配置axios统一配置:
const instance = axios.create({ //创建配置
baseURL: 'https://some-domain.com/api/', //后端接口
timeout: 1000, //超时时间推荐5-8s
headers: {'X-Custom-Header': 'foobar'} //请求头
});
vue中引入axios,需要在main.js入口文件引入
import axios from 'axios' //导入axios
import Vueaxios from 'vue-axios' //导入VUE-axios
Vue.use(Vueaxios,axios); #通过vue.use方法把axios对象挂载到vueaxios
示例:
接下来写拦截代码:
import Vue from 'vue'
import './plugins/axios'
import App from './App.vue'
import Router from './router'
import axios from 'axios'
import Vueaxios from 'vue-axios'
axios.defaults.baseURL = "/api"; //根据前端的跨域方式进行设置
axios.defaults.timeout = 8000; //超时时间
axios.interceptors.response.use(function(response){
let res = response.data; //获取接口返回值
if (res.status == 0){ //判断后端返回的状态码是否正确非零极为错误
return res.data //如果正确取res的data数据返回给用户
}else if (res.status == 10){ //再次判断后端返回的值是否为10如果为10代表以登陆,非10即为未登录
window.location.href = "/#/login"; //跳转login接口进行登陆
}else{
alert (res.msg) //抛出错误
}
});
Vue.use(Vueaxios,axios);
Vue.config.productionTip = false
new Vue({
router:Router,
render: h => h(App)
}).$mount('#app')
示例:
![2~4]_M59UP_~PHFT0S3)O9B.png][2]
总结:
接口拦截在前端很重要,比如请求的拦截啊,让问题在前端就处理,这样后端就省去很多蛮烦,还有后端返回response,我们进行处理返回等详情请看https://www.npmjs.com/package/axios