向 Spotify API 发出 PUT 请求时出现 401 错误

Posted

技术标签:

【中文标题】向 Spotify API 发出 PUT 请求时出现 401 错误【英文标题】:Getting 401 error while making a PUT request to the Spotify API 【发布时间】:2022-01-10 19:57:30 【问题描述】:

我正在尝试发出 put 请求为用户创建播放列表,但我不断收到状态:401,消息:“未提供令牌”错误。有人可以帮我看看我的代码并告诉我我做错了什么吗?

    const createNewPlaylist = () => 
    var user_id = ''
    axios.get(' https://api.spotify.com/v1/me',

        headers:
            'Authorization':"Bearer " + localStorage.getItem("accessToken")
        

    ).then((response)=>
        user_id = response.data.id
        console.log(localStorage.getItem("accessToken"))
        axios.post('https://api.spotify.com/v1/users/'+user_id+'/playlists',
        
            headers:
                'Authorization':"Bearer " + localStorage.getItem("accessToken")
            ,
            data:
                "name": "huhsss",
                "description": "New playlist description",
                "public": false
            
        

    ).then((res)=>
            console.log(res)
    )

    )

我已经为此特定调用添加了所有必需的范围,并且我的令牌实际上适用于我提出的所有其他请求。它甚至适用于我发出的第一个 GET 请求。

【问题讨论】:

【参考方案1】:

对于axios 发布请求,data 是第二个参数,选项(包括标题)是 第三个​​ 参数:

axios.post(
  "https://api.spotify.com/v1/users/" + user_id + "/playlists",
  
    name: "huhsss",
    description: "New playlist description",
    public: false,
  ,
  
    headers: 
      Authorization: "Bearer " + localStorage.getItem("accessToken"),
    ,
  
);

【讨论】:

以上是关于向 Spotify API 发出 PUT 请求时出现 401 错误的主要内容,如果未能解决你的问题,请参考以下文章