首页 > 解决方案 > 如何使用 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' 对这个表达式的类型没有影响

请问如何实现这个逻辑?我知道我需要学习更多的打字稿,但在我学习的时候我会“挨打”。谢谢

标签: javascriptreactjstypescriptaxios

解决方案


您收到该错误的原因是因为您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,
});

推荐阅读