在带有请求体的post请求中指定Axios响应类型

3
我试图同时指定JSON主体和响应类型(它们是不同的,在某些示例中,两者不知何故相同)。
错误消息:
参数类型 '{ grant_type: string; refresh_token: string; }' 不能赋值给类型 'AuthResponse' 的参数。 对象文字只能指定已知属性,而'grant_type'不存在于类型'AuthResponse'中。
这是我定义为我的类型的响应:
export interface AuthResponse {
  token: string;
  token_type: string;

  access_token: string;
  access_token_expires_at: string;

  refresh_token: string;
  refresh_token_expires_at: string;
}

axios的使用:

axios
      .post<AuthResponse>(
        secrets.authURL,//Defined in enclosing class
        {
          grant_type: this.grantType,//Defined in enclosing class
          refresh_token: this.authPayload,//Defined in enclosing class
        },//<-- Defined as data and conflicts with AuthResponse
        {
          headers: {
            Authorization: this.getAuthHeader(),//Defined in enclosing class
            "Content-Type": this.contentType,///Defined in enclosing class
          },
        }
      )
      .then((axiosResp) => {
        const response = axiosResp.data;//<-- Not the type I'd expect
      });

axiosResp.data的类型是{grant_type: ..., refresh_token: ...},而不是AuthResponse

从普通JS示例中可以看出,数据是请求的主体,但不确定为什么会被强制视为响应相同,所以我一定做错了什么。

编辑/回答: 正如@jrsharpe评论所指出的那样,这确实是一个bug,他们刚刚发布了v0.23.0。它修复了bug #4116。所以只需升级到0.23.0+即可。


1
我认为这是个bug:https://github.com/axios/axios/issues/4176 - jonrsharpe
无论是响应错误还是接口错误,响应中的字段和输入的字段完全不同。 - Tony Yip
@jonrsharpe 您是正确的,这似乎是一个错误。为了确认,我正在使用报告中列出的 axios 0.22.0 版本。我将其降级到 0.21.4 版本,现在它可以正常工作了。这就是答案。请发布并指派给您。 - Toguard
1个回答

3

你可以这样输入

interface AuthResponse {
    token: string;
    token_type: string;

    access_token: string;
    access_token_expires_at: string;

    refresh_token: string;
    refresh_token_expires_at: string;
}

interface TBody {
    grant_type: string
    refresh_token: string
}

const t = async (): Promise<void> => {

    const data = await axios.post<AuthResponse, AxiosResponse<AuthResponse, TBody>, TBody>("theurl", {
        grant_type: 'kjkjk',
        refresh_token: "dddf",
    }, {
        headers: {
            Authorization: "dfdfds",
            "Content-Type": "application/json",
        },
    })

    const resu: AuthResponse = data.data

}

根据文档和最近的错误报告,这似乎不是使用库的预期方式。感谢您的贡献! - Toguard
我已经使用axios很长时间了,一点问题都没有。上面的代码是基于“axios”: "^0.23.0"的。你可以试一下,看看没问题的。 - Jerome

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接