怎么对axios进行二次封装

原创
小哥 3年前 (2022-10-20) 阅读数 127 #js教程
文章标签 jsaxios

步骤

  • 引入axios
  • 创建axios实例
  • 设置请求拦截器(request interceptors)
  • 设置响应拦截器(response interceptors)
  • 暴露出去

具体代码

//1. 先引入axios依赖包
import axios from "axios";

//2. axios创建对象
const Server = axios.create({
    baseURL: "", //要在管理后台使用的接口的基地址
    withCredentials: true, //请求跨域时携带cookie
    timeout: 8000, //超时时间
    headers: {
        // Content-Type: application/x-www-form-urlencoded,
        // custome-header:tianliangjiaoyu
    }
})

//3. 定义预拦截器,请求拦截器,请求在发出之前被触发。
Server.interceptors.request.use((config) => {
    //config 接口请求的配置信息
    return config;
}, (error) => {
    //是时候抛出错误消息了
    return Promise.reject(error);
})

//4. 定义后置拦截器,响应拦截器, 在服务器响应数据之前触发,
Server.interceptors.response.use((response) => {
    //响应的数据操作
    return response.data;
}, (error) => {
    //是时候抛出错误消息了
    return Promise.reject(error);
})

//5. 暴露出去
export default Server;
版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除

热门