1、编写基础请求代码

初始文件目录


企业微信截图_0df730a7-22b0-43ce-92ba-06ae2526c814.png

在src目录下
1、先创建一个 index.ts 文件,作为整个库的入口文件,然后我们先定义一个 axios 方法,并把它导出

export default function axios(config) {
  // todo
}

2、在src下创建文件夹types,创建文件index.ts,作为我们项目中定义类型的公用文件

  • 首先定义AxiosRequestConfig
interface AxiosRequestConfig {
  url: string,
  method?: string,
  data?: any,
  params?: any
}

method是可选的,默认应该是get,data和params都是可选的
为了让method传入特定的字符串,我们定义字符串字面量类型

type Method = 'get' | 'GET'
| 'delete' | 'DELETE'
| 'put' | 'PUT'
| 'options' | 'OPTIONS'
| 'head' | 'HEAD'
| 'post' | 'POST'
| 'patch' | 'PATCH'
  • 接下来我们把AxiosRequestConfig中的method属性类型改为method类型
interface AxiosRequestConfig {
  url: string,
  method?: Method,
  data?: any,
  params?: any
}

3、返回到index.ts,继续完善axios方法

import { AxiosRequestConfig } from "./types";

export default function axios(config: AxiosRequestConfig) {
  // todo
}

4、使用XMLHttpRequest发送请求,在src下新建一个xhr.ts的文件,将发送请求的逻辑分离出来

import { AxiosRequestConfig } from "./types";

export default function xhr(config: AxiosRequestConfig): void {
}

5、实现xhr的整体逻辑

import { AxiosRequestConfig } from "./types";

export default function xhr(config: AxiosRequestConfig): void {
  // method和data可能没有, 所以给出默认值
  const { url, method = 'get', data = null } = config
  const request = new XMLHttpRequest()
  request.open(method.toUpperCase(), url)
  request.send()
}

6、在index.ts中引入xhr模块

import { AxiosRequestConfig } from "./types";
import xhr from './xhr'

export default function axios(config: AxiosRequestConfig) {
  xhr(config)
}

7、编写demo

import axios from '../../src/index'
axios({
  url: '/api/demo1/get',
  params: {
    a: 1,
    b: 2
  }
})

至此,我们实现了一个简单的请求,但是可以发现,我们的params没有被用到;我们的request body的数据格式、请求头headers也没有处理;另外我们虽然接收到了响应数据,但是我们没有对响应数据做任何处理。接下来,我们需要处理这些问题。

你可能感兴趣的:(1、编写基础请求代码)