【问题标题】:Axios POST status 400 bad request [duplicate]Axios POST状态400错误请求[重复]
【发布时间】:2019-09-12 13:22:26
【问题描述】:

我正在尝试向 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'
        },
    })

上面的sn-p中code是用户授权码,其他都是服务器常量。问题是我在执行请求时收到以下错误:

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

如您所见,我在请求正文中发送的授权类型是指定的 3 种授权类型之一,但我仍然收到状态 400,我不知道为什么。有任何想法吗?

在此先感谢,因为我确信这是一个很容易回答的愚蠢问题,但我就是看不到它

【问题讨论】:

  • 您的 ACCESS_URL 是否与您的脚本在同一个域中?如果没有,您是否为 ACCESS_URL 启用了 CORS?
  • 不,它不在我的域中。 ACCESS_URL 是 spotify web api。

标签: httprequest axios http-status-code-400


【解决方案1】:

请参阅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'
  }
})

【讨论】:

  • 这样做我现在得到一个 415 响应代码
【解决方案2】:

我找到了解决方案。我不得不像这样使用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'
    }
}
)

感谢大家的帮助

【讨论】:

    猜你喜欢
    • 2021-10-13
    • 1970-01-01
    • 2021-01-12
    • 2019-09-13
    • 2017-09-07
    • 2015-04-01
    • 1970-01-01
    • 2020-01-13
    • 2020-08-30
    相关资源
    最近更新 更多