Axios secondary packaging and use

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
  })
}

Guess you like

Origin blog.csdn.net/weixin_44694682/article/details/128768335