赞
踩
最近工作繁忙,继上篇react+typescript构建h5项目已经一个月没有更新内容了。最近有个 h5 的项目正好使用到之前搭建的模板,于是将上述的模板拉过来,配个路由就直接可以使用了,节省不少时间。现在再将 axios 添加到项目中。这项下次再使用到的时候就会更加轻松。
首先安装 axios npm i axios -S
,引入 axios,添加默认配置,其中基础路径 baseURL,一般是在.env 中拿在 cra 中使用 env,如果是复杂的情况也可以单独建一个文件,通过 window.location.host 在不同环境的区别等等修改 baseURL
// 引入axios和后面会用到的ts类型 import axios, { AxiosRequestConfig, AxiosRequestHeaders, AxiosInstance, AxiosResponse, } from "axios"; // 使用QueryString,当content-type为表单时“application/x-www-form-urlencoded” 将参数拼接为类似于get请求的形式 (a=1&b=3) import QueryString from "qs"; import { message } from "antd"; interface RequestConfig extends AxiosRequestConfig { headers: AxiosRequestHeaders; } const defaultConfig: RequestConfig = { baseURL: "", timeout: 120 * 1000, //超时 withCredentials: true, //允许跨域携带cookie headers: { // content-type 可以先和后端沟通使用JSON还是表单,后面有少数不一样的特殊处理就行 "content-type": "application/x-www-form-urlencoded", }, };
上面就实现了基础配置的添加
const request = (
method: "get" | "post" | "put" | "delete" | "patch" | "head" | "options",
url: string,
params?: any,
config?: AxiosRequestConfig, //自定义的配置
interceptor?: {
request?:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。