初始化
1 | create-react-app project-axios --typescript |
删除 src/ 下的内容,新建 index.tsx
新建 src/api.js 作为后台接口
1 | let express = require('express'); |
运行后台接口程序 nodemon api.js
访问: http://localhost:8080/get?name=jiafei&age=18 浏览器返回 {“name”:”jiafei”,”age”:”18”}
开始
get请求
src/index.tsx
1 | import axios, { AxiosResponse} from 'axios'; |
运行:yarn start
访问:http://localhost:3000/get?name=jiafei&password=123
查看源码
github 搜索 axios
点开 index.js
module.exports = require(‘./lib/axios’);
找到 /lib/axios.js 它上面创建实例的方法
1 | /** |
手写axios
新建 /lib/index.tsx
1 | import Axios from './Axios'; |
新建 /lib/axios.tsx
1 | export default class Axios { |
新建 /lib/types.tsx
1 | export type Methods = 'get' | 'GET' | 'post' | 'POST' | 'put' | 'PUT' | 'delete' | 'DELETE' | 'options' | 'OPTIONS'; |
*现在来看 src/index.tsx 中line17 请求的返回参数 * 如下:
这里点击查看 line16 (response: AxiosResponse)
中 AxiosResponse
源码如下:
1 | export interface AxiosResponse<T = any> { |
在我们自己的 /lib/types.tsx中添加如下代码:
1 | // 这个泛型T代表响应体的类型 |