如何从Spotify API获取信息以及如何在JSON中转换响应?

时间:2019-05-20 23:56:05

标签: javascript json ajax api spotify

我对javascript和API还是陌生的,所以我仍在学习,但是我不了解有关API的课程,因此现在我只停留在项目的这一部分。

这就是我要做的,我必须创建一个React应用,该应用允许用户创建一个播放列表,然后将其发送到Spotify,因此我需要从Spotify中获取音乐数据,然后保存该播放列表在Spotify中。

const client_id = "CLIENT_ID"
const redirect_uri = "http://localhost:3000/"

let accessToken;
let url = "https://accounts.spotify.com/authorize?client_id=CLIENT_ID&redirect_uri=http:%2F%2Fexample.com%2Fcallback&scope=user-read-private%20user-read-email&response_type=token&state=123"
const Spotify = {
  getAccessToken() {
    if (accessToken) {
      return accessToken;
    } else if (window.location.href.match(/access_token=([^&]*)/ & /expires_in=([^&]*)/)) {
      accessToken = window.location.href.match(/access_token=([^&]*)/);
      let expiresIn = window.location.href.match(/expires_in=([^&]*)/);
      window.setTimeout(() => accessToken = '', expiresIn * 1000);
      window.history.pushState('Access Token', null, '/');
    } else {
      window.location(`https://accounts.spotify.com/authorize?client_id=${client_id}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirect_uri}`);
    }
  },

  search(term) {
    const response = fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {
      method: 'GET',
      headers: {Authorization: `Bearer ${accessToken}`}
    })
    if (response.ok) {
      const jsonResponse = response.json().then(
        jsonResponse.map((track) => {
          ID: track.id,
          Name: track.name,
          Artist: track.artists[0].name,
          Album: track.album.name,
          URI: track.uri
      }))
    }
  }

  savePlaylist(namePlaylist, [])
};





export default Spotify

很抱歉,如果它很混乱,但是我是新手,并且对本课没有任何了解,所以我什至不知道我期望什么,但告诉我还需要说明什么。错误之一是在此部分:

    if (response.ok) {
      const jsonResponse = response.json().then(
        jsonResponse.map((track) => {
          ID: track.id,
          Name: track.name,
          Artist: track.artists[0].name,
          Album: track.album.name,
          URI: track.uri
      }))
    }

错误告诉我unexpected token:之后谈论"ID", "Name", "Artist", "Album" and "URI",也告诉我expected ';',但我认为这没有逻辑,因此我真的需要一些帮助而且我知道我可能还不清楚,所以请问我什么让它更清楚。

0 个答案:

没有答案