首页 > 移动平台 > 详细

axios拦截器的使用

时间:2020-07-10 01:23:24      阅读:96      评论:0      收藏:0      [点我收藏+]

src\network\request.js

import axios from ‘axios‘
//创建一个叫request的实例
export function request(config) {
   //1 创建实例
   const instance = axios.create({
     baseURL:‘http://123.207.32.32:8000‘,
     timeout:5000
   })
   //2 拦截器
  //2.1请求拦截
  instance.interceptors.request.use(config=>{
    //console.log(config) //发送成功
    //请求拦截的作用
    //1 如果发送请求 不符合浏览器的某些要求,我们在这里进行某些操作 比如说 添加某些特殊的header、
    //2 比如每次发送网络请求时,都希望在界面中显示一个请求的图片(转啊转的那种)
    //3 某些网络请求(比如登录 token) 必须携带一些特殊的信息 如果没有携带 就拦截 跳转到登录的地方
    return config       //如果不返回 config会被拦截
  },err=>{
    //console.log(err)    //发送失败
    return err
  })
  //响应拦截
  instance.interceptors.response.use(res=>{
    //console.log(res);
    //res会返回一堆东西,但我们真正需要的是res.data
    return res.data;
  },err=>{
    console.log(err);
    return err;
  })
   //3 发送网络请求
   //为什么 instance 可以直接调.then
   //因为AxiosInstance的返回值本身就是一个Promise 只要直接return就可以了
   return instance(config)
}

 

axios拦截器的使用

原文:https://www.cnblogs.com/polax/p/13277148.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!