vue-06 vue使用axios接口错误拦截

目录

1.axios

1.1官方文档

1.2基本使用

1.2.1get请求

1.2.2post请求

1.2.3执行多个并发请求

1.2.4拦截器

1.3统一报错、未登录同意拦截、请求值、返回值同意处理示例

1.3.1main.js


1.axios

1.1官方文档

http://www.axios-js.com/zh-cn/docs/

1.2基本使用

1.2.1get请求

get请求需要添加params对象或者参数跟在请求地址后面

// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// 上面的请求也可以这样做
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

1.2.2post请求

post请求不需要加params

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

1.2.3执行多个并发请求

通常用在需要多个请求添加loading加载场景下使用

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求现在都执行完成
  }));

1.2.4拦截器

在请求或响应被 then 或 catch 处理前拦截它们。

request拦截器针对用户请求进行拦截,通过config可以取到参数,对参数进行操作,比如对参数中的日期格式字符串转时间戳等等;

response 可以根据接口规范做错误拦截

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

1.3统一报错、未登录同意拦截、请求值、返回值同意处理示例

1.3.1main.js

import Vue from 'vue'
import router from "./router";
import axios from "axios";
import VueAxios from "vue-axios";
import App from './App.vue'
//设置axios 基础值
//根据前端跨域做调整,使用代理可以把api给替换为空
axios.defaults.baseURL ='/api';
//推荐是8秒
axios.defaults.timeout =8000;
Vue.use(VueAxios, axios);
//生产环境的提示
Vue.config.productionTip = false;
//接口规范如下
/*{
  status:0,
  data:[],
  msg:""
}*/
//接口错误拦截
axios.interceptors.response.use(function (response) {
    //取到返回的值
    let res = response.data;
    if (res.status == 0) {
      //成功
        res.data;
    }else if(res.status == 10){
      //未登录状态码,跳转登陆页面
      window.location.href='/#/login';
    }else{
      alert(res.msg);
    }
});
new Vue({
    router: router,
    render: h => h(App),
}).$mount('#app');

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值