Skip to content

Commit

Permalink
feat: ✨ 新增网络请求Axios v1
Browse files Browse the repository at this point in the history
  • Loading branch information
guokaigdg committed Feb 21, 2023
1 parent c5269c7 commit 27cd67f
Show file tree
Hide file tree
Showing 16 changed files with 434 additions and 25 deletions.
16 changes: 11 additions & 5 deletions README.md
@@ -1,6 +1,10 @@
<h1 align="center">react 模板</h1>
<br/>

<center>
<img src='./docs/images/home.png' style='width: 75%'/>
</center>

## 👨🏻‍💻 项目说明

- react 模板, 一个比 CRA 更丰富的模板
Expand All @@ -14,11 +18,10 @@
- React Hook
- TypeScript v4
- webpack v5
- axios
- axios v1
- mobx v6
- mobx-react-lite v3
- react-router-dom v6
- postcss-px-to-viewport

## ⌛️ 安装项目依赖

Expand Down Expand Up @@ -127,7 +130,10 @@ merge 🔀 合并分支
```

## 技术栈说明
## 🚀 陆续新增内容:

- React18
- TypeScript
- ① 样式 ✅ 2023/2/6 日提交 [config: 🔧  新增样式文件(css/less/sass/postCss)处理](https://github.com/guokaigdg/react-enterprise-template/commit/11fb415bac609dfa7474a1ee2db93ccb4a350a51)
- ② 代码规范 ✅ 2023/2/7 日提交 [config: 🔧  新增 Prettier/ESlint/StyleLint/EditorConfig 代码规范](https://github.com/guokaigdg/react-enterprise-template/commit/87dd1ca333f81203dd245a6eb40479a0745f096f)
- ③ 路由 ✅ 2023/2/8 日提交 [config: 🔧 新增路由管理 react-router-dom v6](https://github.com/guokaigdg/react-enterprise-template/commit/239446d0709eb52bad2b48af4983eef91c49f60d)
- ④ 网络请求 ✅ 2023/2/21 日提交
- ⑤ 数据共享 ✅ [feature: ✨  新增状态管理 Mobx v6](https://github.com/guokaigdg/react-enterprise-template/commit/992e1884943d4f8bda836f48c60df473418397d7)
Binary file added docs/images/home.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
68 changes: 60 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Expand Up @@ -105,6 +105,8 @@
"webpackbar": "^5.0.2"
},
"dependencies": {
"axios": "^1.3.3",
"axios-retry": "^3.4.0",
"mobx": "^6.8.0",
"mobx-react-lite": "^3.4.0",
"react": "^18.2.0",
Expand Down
31 changes: 31 additions & 0 deletions src/api/index.ts
@@ -0,0 +1,31 @@
/*
* @file: 所有的接口列表
* 宝可梦api https://pokeapi.co/about
*/

import http from '../http';
import {pokemonOptions} from '@/interface/http';

/**
* @function get
* @description 请求测试
*/

export function fetchPokemon(data: pokemonOptions) {
return http({
url: ' https://pokeapi.co/api/v2/pokemon',
params: data
});
}
/**
* @function post
* @description 请求测试
*/

export function fetchPostTest(data: any) {
return http({
url: '/xxx/list',
method: 'post',
data
});
}
6 changes: 6 additions & 0 deletions src/http/README.md
@@ -0,0 +1,6 @@
1. 实现请求拦截
2. 实现响应拦截
3. 常见错误信息处理
4. 请求头设置
5. api 集中式管理
6. 重复发送请求
75 changes: 75 additions & 0 deletions src/http/index.ts
@@ -0,0 +1,75 @@
/*
* @Author: guokai05
* @Date: 2023-02-19 22:31:15
* @LastEditors: guokai05
* @LastEditTime: 2023-02-21 16:18:27
*/
import axios from 'axios';
import axiosRetry from 'axios-retry';
import {InternalAxiosRequestConfig, AxiosRequestConfig, AxiosResponse, AxiosError} from 'axios';
const whiteRetry = new Set(['ECONNABORTED', undefined, 0]);
// import {baseURL} from '@/utils/variable';

// 创建 axios 请求实例
const serviceAxios = axios.create({
baseURL: '', // 接口请求地址
timeout: 15 * 1000, // 请求超时设置
withCredentials: false, // 跨域请求是否需要携带 cookie
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
validateStatus() {
// 使用async-await,处理reject情况较为繁琐,所以全部返回resolve,在业务代码中处理异常
return true;
}
});

axiosRetry(serviceAxios, {
retries: 2, // 重复请求次数
shouldResetTimeout: true, // 重置超时时间
retryDelay: (retryCount) => {
return retryCount * 10000; // 重复请求延迟
},
retryCondition: (err) => {
// true为打开自动发送请求,false为关闭自动发送请求
const {code, message} = err;
return whiteRetry.has(<string>code) || message.includes('timeout');
}
});

// 请求拦截器
serviceAxios.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
return config;
},
(err: AxiosError) => {
return Promise.reject(err);
}
);

// 响应拦截器
serviceAxios.interceptors.response.use(
(res: AxiosResponse) => {
return res;
},
(err: AxiosError) => {
return Promise.reject(err);
}
);

// 统一发起请求的函数
async function request<T>(options: AxiosRequestConfig) {
try {
const response = await serviceAxios.request<T>(options);
const {status, data} = response;
// 处理 HTTP 状态码
if (status < 200 || status >= 500) {
return Promise.reject();
}
return Promise.resolve(data);
} catch (error) {
return Promise.reject(error);
}
}

export default request;
4 changes: 4 additions & 0 deletions src/interface/http.ts
@@ -0,0 +1,4 @@
export interface pokemonOptions {
offset?: number;
limit: number;
}
2 changes: 1 addition & 1 deletion src/router/index.tsx
Expand Up @@ -15,7 +15,7 @@ const About = Suspenselazy(() => import(/* webpackChunkName:"about" */ '@/view/A
const routes: RouteObject[] = [
{
path: '/',
element: <Navigate to='home' /> // 重定向
element: <Navigate to='home/two' /> // 重定向
},
{
path: 'home',
Expand Down
21 changes: 20 additions & 1 deletion src/store/global/index.ts
@@ -1,17 +1,36 @@
import {makeAutoObservable} from 'mobx';
import {makeAutoObservable, runInAction} from 'mobx';
import {fetchPokemon} from '@/api';
import {pokemonOptions} from '@/interface/http';

class Global {
constructor() {
makeAutoObservable(this);
}
count = 0;
name = 'react';
data: any = [];
loading = true;

addCount = () => {
this.count++;
};
setName = (data: string) => {
this.name = data;
};

getFetchGetTest = async (params: pokemonOptions) => {
try {
const result: any = await fetchPokemon(params);
const {results} = result;
runInAction(() => {
this.data = results;
this.loading = false;
});
} catch (err) {
console.log(err);
this.loading = false;
}
};
}

const globalStore = new Global();
Expand Down

0 comments on commit 27cd67f

Please sign in to comment.