简体   繁体   English

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

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

I'm trying to add a song to the playback queue using this endpoint:我正在尝试使用端点将歌曲添加到播放队列:

   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);
    }
   
   
}

I'm getting a status 401 error with a message that says no token provided.我收到状态 401 错误,并显示未提供令牌的消息。 But when I console.log the token it shows up.但是当我 console.log 显示它的令牌时。

I haven't worked with the Spotify API yet, however, according to their docs , you need to send a POST request, not a PATCH, which is what you used.我还没有使用过 Spotify API,但是,根据他们的文档,你需要发送一个 POST 请求,而不是你使用的 PATCH。

Use axios.post() instead of axios.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);
  }
};

The second param of your post request should be body and the third param should be headers .您的 post 请求的第二个参数应该是body ,第三个参数应该是headers Also, you haven't added all the headers as mentioned in the documentation.此外,您还没有添加文档中提到的所有标题。

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

Get your access token from here: https://developer.spotify.com/console/post-queue/从这里获取您的访问令牌: https ://developer.spotify.com/console/post-queue/

If it still doesn't work try the curl method as mentioned in their docs and if it works, switch it to axios.如果它仍然不起作用,请尝试他们文档中提到的 curl 方法,如果有效,请将其切换到 axios。

I had the exact same issue as you, what I realised was I was passing the header as data rather than as config.我和你有完全相同的问题,我意识到我将标头作为数据而不是配置传递。 This code below should work for you as it works for me.下面的代码应该对你有用,因为它对我有用。

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