繁体   English   中英

如何使用 Axios 进行 Spotify Api 发布请求

[英]How to do Spotify Api Post Request using Axios

我正在尝试使用端点将歌曲添加到播放队列:

   const add = async () => {
   

    try {
      
      const url = `https://api.spotify.com/v1/me/player/queue?uri=${songUrl}&device_id=${deviceId}`
     
      await axios.patch(url, {
        headers: {
            Authorization: `Bearer ${to}`
        },
    })
    } catch (error) {
      console.log(error);
    }
   
   
}

我收到状态 401 错误,并显示未提供令牌的消息。 但是当我 console.log 显示它的令牌时。

我还没有使用过 Spotify API,但是,根据他们的文档,你需要发送一个 POST 请求,而不是你使用的 PATCH。

使用axios.post()而不是axios.patch()

const add = async (songUrl, deviceId, token) => {
  try {
    const url = `https://api.spotify.com/v1/me/player/queue?uri=${songUrl}&device_id=${deviceId}`;

    await axios.post(url, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
  } catch (error) {
    console.log(error);
  }
};

您的 post 请求的第二个参数应该是body ,第三个参数应该是headers 此外,您还没有添加文档中提到的所有标题。

headers: {
      Accept: 'application/json',
      Authorization: 'Bearer ' + newAccessToken,
      'Content-Type': 'application/json',
}

从这里获取您的访问令牌: https ://developer.spotify.com/console/post-queue/

如果它仍然不起作用,请尝试他们文档中提到的 curl 方法,如果有效,请将其切换到 axios。

我和你有完全相同的问题,我意识到我将标头作为数据而不是配置传递。 下面的代码应该对你有用,因为它对我有用。

const add = async () => {
  try { 
    const url = `https://api.spotify.com/v1/me/player/queue?uri=${songUrl}&device_id=${deviceId}`
    await axios.post(url, null,{
      headers: {
        Authorization: `Bearer ${to}`
      },
    })
  } catch (error) {
    console.log(error);
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM