【问题标题】:URLSearchParam type {property: value} is not assignable to undefined & Argument Type {property: value} not assignable to {property: value}URLSearchParam 类型 {property: value} 不可分配给未定义和参数类型 {property: value} 不可分配给 {property: value}
【发布时间】:2022-08-17 11:47:36
【问题描述】:

当我尝试执行以下代码时,我不断收到此错误。基本上,它接受给定的刷新令牌并将带有 URLSearchParams 的 POST 请求发送到 URL。但由于某种原因,URLSearch 参数不断抛出错误。

代码

const getAccessToken = async () => {
  const response = await fetch(TOKEN_ENDPOINT, {
    method: \'POST\',
    headers: {
      Authorization: `Basic ${basic}`,
      \'Content-Type\': \'application/x-www-form-urlencoded\',
    },
    body: new URLSearchParams({
      grant_type: \'refresh_token\',
      refresh_token,
    }),
  })
  return response.json()
}

其中refresh_token 是由环境变量定义的常量。

错误

Argument of type \'{ grant_type: string; refresh_token: string | undefined; }\' is not assignable to parameter of type \'string | string[][] | Record<string, string> | URLSearchParams | undefined\'.
  Type \'{ grant_type: string; refresh_token: string | undefined; }\' is not assignable to type \'undefined\'.ts(2345)

    标签: node.js typescript next.js request typescript2.0


    【解决方案1】:

    为了解决这个问题,我所做的就是完全删除 URLSearchParams 函数,然后手动编写搜索参数。如果其他人知道如何在仍然使用 URLSearchParams 的同时解决此问题,请告诉我。

    body: new URLSearchParams({
            grant_type: 'refresh_token',
            refresh_token,
          })
    
    body: `grant_type=refresh_token&refresh_token=${refresh_token}`
    

    最终代码

    const getAccessToken = async () => {
      const response = await fetch(TOKEN_ENDPOINT, {
        method: 'POST',
        headers: {
          Authorization: `Basic ${basic}`,
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `grant_type=refresh_token&refresh_token=${refresh_token}`
      })
      return response.json()
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      • 2019-09-06
      • 1970-01-01
      • 2022-07-20
      • 2018-11-05
      • 2017-07-29
      相关资源
      最近更新 更多