如何使用axios create创建promise实例

时间:2019-11-27 12:27:23

标签: javascript reactjs typescript axios

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

请问如何实现这种逻辑?我知道我需要学习更多的打字稿,但是在学习的过程中我会被“打败”。谢谢

3 个答案:

答案 0 :(得分:1)

function Axios(...)不是异步函数,因此不需要使用await,因为它不会返回诺言,这就是您获得'await' has no effect on the type of this expression的原因。

答案 1 :(得分: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 :(得分:1)

我认为您需要使用拦截器

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
}