Axios 二次封装并使用

index.js

import axios from "axios";

let token = localStorage.getItem("token");
// let token = "123213";
class Request {
  // 自定义变量
  instance;
  constructor(config) {
    // console.log(config)
    // 创建axios 实例,变量接收
    this.instance = axios.create(config);
    // 添加请求拦截器
    this.instance.interceptors.request.use(
      (config) => {
        config.headers.Authorization = token;
        console.log(config, 123)
        return config;
      },
      (error) => {
        return error;
      }
    );
    // 添加相应拦截器
    this.instance.interceptors.response.use(
      (res) => {
        return res.data;
      },
      (error) => {
        console.log(error, 2)
        return error;
      }
    );
  }
  // 2
  request(config) {
    return new Promise((resolve, reject) => {
      this.instance.request(config).then((res) => {
        return resolve(res);
      }).catch((error) => {
        return reject(error);
      });
    });
  }


  // 1
  get(config) {
    return this.request({
      ...config,
      method: "GET",
    });
  }
  post(config) {
    return this.request({
      ...config,
      method: "POST",
    });
  }
  delete(config) {
    return this.request({
      ...config,
      method: "DELETE",
    });
  }
}

export default Request;

config.js

const baseurl = "http://localhost:8080/api";


import Request from './index.js'

export const request = new Request({
  baseURL: baseurl,
  timeout: 1000
})

Login / login.js

import { request } from '../config.js'

// 获取登录验证码
export const getLoginCode = () => {
  return request.get({
    url: '/code'
  })
}

// 登录
export const login = (data) => {
  return request.post({
    url: '/auth/login',
    data,
    showLoading: true
  })
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黑白两客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值