javascript - 如何使用 axios create 创建 Promise 实例
问题描述
我是 TypeScript 的新手,所以我边走边学。我想创建一个 axios 实例以在我的代码中重用,我只需要在需要的地方传递道具。我使用反应。
// in a utils folder
// axios.ts
import axios from 'axios'
type Method =
| 'get' | 'GET'
| 'delete' | 'DELETE'
| 'head' | 'HEAD'
| 'options' | 'OPTIONS'
| 'post' | 'POST'
| 'put' | 'PUT'
| 'patch' | 'PATCH'
| 'link' | 'LINK'
| 'unlink' | 'UNLINK'
interface AxiosProps {
/** Web URL */
url: string,
/**
* POST method: GET, POST, PUT, DELETE
* @default GET
*/
method?: Method,
/** Header options */
header?: object,
/** Optional Data for POST */
data?: object,
/** Optional params */
params?: object
}
export function Axios(props: AxiosProps) {
/**
* Creates an axios instance.
*
* @see https://github.com/axios/axios
* @return Promise
*/
const instance = axios.create({
baseURL: process.env.REACT_APP_API_ENDPOINT,
headers: { 'Content-Type': 'application/json' },
url: props.url, // must have a starting backslash: /foo
params: props.params,
data: props.data,
withCredentials: true,
})
return instance
}
我从axiosMethod
得到了类型。
现在,使用实例:
import {Axios} from '../utilities/axios'
// I'd like to achieve this in an async function:
const {data} = await Axios({url: '/foo' /**, method: 'POST' **/})
console.log(data)
以上,TS抱怨:
'await' 对这个表达式的类型没有影响
请问如何实现这个逻辑?我知道我需要学习更多的打字稿,但在我学习的时候我会“挨打”。谢谢
解决方案
您收到该错误的原因是因为您Axios
是 axios 实例。我假设您想使用request
具有以下类型签名的 axios 实例的功能:
request<T = any, R = AxiosResponse<T>> (config: AxiosRequestConfig): Promise<R>;
此外,您不能在文件的“全局”上下文中使用异步操作。您应该定义一个异步函数,如下所示:
async function fetchData(): Promise<void> {
const { data } = await Axios.request({ url: '/foo', method: 'GET' });
...
}
fetchData();
一些编码风格提示: 最佳实践是只对类使用大写。在你的情况下,你可以做一些事情,比如
export const axiosInstance = axios.create({
baseURL: process.env.REACT_APP_API_ENDPOINT,
headers: { 'Content-Type': 'application/json' },
url: props.url, // must have a starting backslash:
params: props.params,
data: props.data,
withCredentials: true,
});
推荐阅读
- cassandra - 如何强制 Commit log 提交到 memtable?
- kibana - 如何从 kibana 过滤器的下拉列表中删除标签
- json - 在 JSON 中生成“|”到 YML
- html - 右侧按钮下方的文字
- java - itext 7(java)将新页面上的图像添加到现有pdf文档的末尾
- graphql - Hasura 查询的工作方式类似于 SQL 内连接
- ruby - 什么是 << 在 ruby 中代表整数
- git - git mergetool 在cherry-pick 中显示了许多不相关的更改
- php - How to Filter Content passed to a WordPress Shortcode
- c++ - Using auto to a variable assigned ot a function that return const ref