【问题标题】:Getting "Request failed with status code 401" error when trying to create a playlist in Spotify using their API尝试使用其 API 在 Spotify 中创建播放列表时出现“请求失败,状态码为 401”错误
【发布时间】:2020-04-21 19:55:48
【问题描述】:

这是我正在使用的代码:

    await axios.post(arg.url,
        {
            headers: {
                "Content-Type": "application/json",
                Authorization: `Bearer ${SPYauthToken}`
            },
            params: {name: "playlist"},

        }
    )

我之前已经提供了对所有必要范围的访问权限并获得了相应的身份验证令牌,但是当我尝试使用我提供的代码创建播放列表时,我收到一条错误消息,提示“请求失败,状态码 401”。

当我尝试在 Spotify 自己的 API 站点中创建播放列表时,它也不起作用:https://developer.spotify.com/console/post-playlists/ 使用他们自己的示例单击“尝试”后,没有任何反应,也没有为我创建播放列表。

我做错了什么,还是 Spotify 必须解决的问题?

谢谢!

【问题讨论】:

  • 您在授权标头上缺少引号,无论如何,如果 curl 有效,您是否尝试过?
  • 嗨,它确实使用 curl 工作。所以这绝对是我的事。无论如何添加引号都不能解决问题。
  • 我使用 fetch 修复了它。出于某种原因,Axios 拒绝处理 POST 请求
  • 请看我的回答,也许它可以解决问题

标签: javascript react-native axios spotify


【解决方案1】:

没试过,但你可以做以下

    // request data object
    const data = {
        name: "playlist"
    };

    // set the headers
    const config = {
       headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${SPYauthToken}`
        }
    };

await axios.post(arg.url, data, config);
// maybe you need to stringify data so
await axios.post(arg.url, JSON.stringify(data), config);

【讨论】:

  • 这个解决方案也可以,除了使用 fetch 之外(不需要字符串化)谢谢!
【解决方案2】:
    await axios.post(arg.url,
        {
            headers: {
                "Content-Type": "application/json",
                "Authorization": `Bearer ${SPYauthToken}`
            },
            params: {name: "playlist"},

        }
    )

你没有在授权周围使用引号

【讨论】:

  • 当我在名称中不使用破折号时,我从来没有使用过它们,它已经奏效了。无论如何,添加它们并没有解决它。
【解决方案3】:

我使用 fetch 修复了它:

    const data = { name: 'playlist' };

    fetch(arg.url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          "Authorization": `Bearer ${SPYauthToken}`
        },
        body: JSON.stringify(data),
      })
      .then((response) => response.json())

完美运行。 Axios 似乎无法使用 POST,至少不像预期的那样,所以我可能会停止使用它。

感谢所有回答的人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2018-06-13
    • 2015-08-19
    • 1970-01-01
    • 2021-03-11
    • 2017-03-15
    • 2016-10-22
    相关资源
    最近更新 更多