【问题标题】:How to create promise instance with axios create如何使用 axios create 创建 Promise 实例
【发布时间】:2019-11-27 12:27:23
【问题描述】:

我是 TypeScript 的新手,所以我边走边学。我想创建一个 axios 实例以在我的代码中重用,我只需要在需要的地方传递道具。我正在使用 React。

// 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
}

我从axios 得到Method 类型。

现在,使用实例:

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' 对这个表达式的类型没有影响

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

【问题讨论】:

    标签: javascript reactjs typescript axios


    【解决方案1】:

    您收到该错误的原因是因为您的 Axios 是一个 axios 实例。我假设您想使用 axios 实例的 request 函数,该函数具有以下类型签名:

    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,
    });
    

    【讨论】:

      【解决方案2】:

      我认为你需要使用拦截器

      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,
          })
      
          instance.interceptors.response.use(
            response => response,
            error => error,
          );
      
          return instance
      }
      

      【讨论】:

        【解决方案3】:

        function Axios(...) 不是异步函数,所以没有必要使用await,因为它不返回承诺,这就是你得到'await' has no effect on the type of this expression 的原因。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-11-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-10
          • 1970-01-01
          • 1970-01-01
          • 2019-11-23
          相关资源
          最近更新 更多