Axios POST状态400错误请求[重复]

问题描述 投票:0回答:2

这个问题与以下内容完全相同:

我正在尝试向spotify web api发出POST请求。我正在使用这段代码:

axios.post(ACCESS_URL, {
    "grant_type": 'authorization_code',
    "code": code,
    "redirect_uri": REDIRECT_URI
},
    {
        headers: {
            "Authorization": "Basic " + Buffer.from(CLIENT_ID + ":" + CLIENT_SECRET).toString("base64"),
            'Content-Type': 'application/x-www-form-urlencoded'
        },
    })

在上面的代码片段中,code是用户授权代码,其他所有内容都是服务器常量。问题是我在执行请求时收到以下错误:

 error: 'unsupported_grant_type',
        error_description: 'grant_type must be client_credentials, authorization_code or refresh_token' 

正如您所看到的,我在请求正文中发送的授权类型是3种指定的授权类型之一,但我仍然获得状态400,我无法弄清楚原因。有任何想法吗?

提前谢谢,因为我确信这是一个简单的答案,这是一个愚蠢的问题,但我只是没有看到它

httprequest axios http-status-code-400
2个回答
0
投票

有关类似问题,请参阅Unsupported grant type error when requesting access_token on Spotify API with Meteor HTTP

Spotify期望查询字符串参数中的grant_type,而不是post请求体中。实际上,上述问题/答案中的配置看起来与axios配置非常相似。只需将前三个参数包装到params对象中:

axios.post(ACCESS_URL, {
 params: {
    "grant_type": 'authorization_code',
    "code": code,
    "redirect_uri": REDIRECT_URI
  },
  headers: {
    "Authorization": "Basic " + Buffer.from(CLIENT_ID + ":" + CLIENT_SECRET).toString("base64"),
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})

0
投票

我找到了解决方案。我不得不使用querystring对数据进行编码,如下所示:

return axios.post(ACCESS_URL,querystring.stringify({
        "grant_type": 'authorization_code',
        "code": code,
        "redirect_uri": REDIRECT_URI
    }),
    {headers: {
        "Authorization": "Basic " + Buffer.from(CLIENT_ID + ":" + CLIENT_SECRET).toString("base64"),
        'Content-Type': 'application/x-www-form-urlencoded'
    }
}
)

谢谢大家的帮助

© www.soinside.com 2019 - 2024. All rights reserved.