创建入口文件

  1. import { AxiosRequestConfig } from './types/index'
  2. import xhr from './xhr'
  3. const axios = (params: AxiosRequestConfig) => {
  4. xhr(params)
  5. }
  6. export default axios

定义 AxiosRequestConfig 接口类型

  1. export type Method =
  2. | 'get' | 'GET'
  3. | 'delete' | 'DELETE'
  4. | 'head' | 'HEAD'
  5. | 'options' | 'OPTIONS'
  6. | 'post' | 'POST'
  7. | 'put' | 'PUT'
  8. | 'patch' | 'PATCH';
  9. export interface AxiosRequestConfig {
  10. url: string
  11. method: Method
  12. data?: any
  13. params?: any
  14. }

定义 xhr 方法

  1. import { AxiosRequestConfig } from "./types";
  2. export default function xhr(config: AxiosRequestConfig) {
  3. const { url, method = 'get', data = null, params = null } = config
  4. const request = new XMLHttpRequest()
  5. request.open(method.toLowerCase(), url, true)
  6. request.send(data)
  7. }