Spotify play endpoint won't recognize uri

时间:2019-02-24 00:23:28

标签: javascript api axios spotify

I've built a Spotify player in JS and I have a function that sends playback commands. So far, it successfully modifies playback for everything except playing a specific track.

When I try to pass in a one item array of track URI's to play a particular song, it simply resumes playing the current track and not the specified URI.

I'm able to get this endpoint to work on their test site as well as in Postman with the same syntax, but it's not working in my code. Any insight would be appreciated.

function playerAction(token, action, desiredValue) {
  var method;
  var params = {};
  switch (action) {
    case "next":
      method = "post";
      break;
    case "previous":
      method = "post";
      break;
    case "shuffle":
      method = "put";
      params = { state: desiredValue };
      break;
    case "volume":
      method = "put";
      params = { volume_percent: desiredValue };
      break;
    case "play":
      method = "put";
      if (desiredValue) params = { uris: [desiredValue] };
      break;
    default:
      method = "put";
  }
  return axios({
    method: method,
    url: `https://api.spotify.com/v1/me/player/${action}`,
    params: params,
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
}

I also added a console.log into the play case just to make sure the data was making it there. Output seems to confirm that's working:

you asked spotify.js to play with desiredValue: spotify:track:2GIfOOa8hAywfzZptFz3xK

1 个答案:

答案 0 :(得分:0)

在通过console.log盯着axios的响应之后,我注意到在配置中,一个名为“ data”的键的值未定义。因此,很自然地,我在axios调用中添加了一个名为data的键,并将带有uri键的对象移到了那里。瞧,它奏效了。

function playerAction(token, action, desiredValue) {
  var method;
  var params = {};
  var data = {};
  switch (action) {
    case "next":
      method = "post";
      break;
    case "previous":
      method = "post";
      break;
    case "shuffle":
      method = "put";
      params = { state: desiredValue };
      break;
    case "volume":
      method = "put";
      params = { volume_percent: desiredValue };
      break;
    case "play":
      method = "put";
      if (desiredValue) data = { uris: [desiredValue] };
      break;
    default:
      method = "put";
  }
  return axios({
    method: method,
    url: `https://api.spotify.com/v1/me/player/${action}`,
    params: params,
    data: data,
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
}