I am stuck on an error near the end of the Jammming project.
My response from the Spotify API comes back as this when console logged:
It is a cors-anywhere response instead of Spotify data for the search. Looks like it is not redirecting from cors-anywhere proxy? This shows up like this whether or not I have the cors-anywhere prefix in the request URL. Below is my code:
Spotify.js:
let accessToken;
const clientID = '39e5a52079bd485f8dab3d4c0556de73';
const redirectURI = "http://localhost:3000/";
const Spotify = {
getAccessToken() {
if (accessToken) {
return accessToken;
}
// check for access token match
const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);
const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);
if (accessTokenMatch && expiresInMatch) {
accessToken = accessTokenMatch[1];
const expiresIn = Number(expiresInMatch[1]);
// clear parameters and allow us to acces new access access_token
window.setTimeout(() => (accessToken = ""), expiresIn * 1000);
window.history.pushState("Access Token", null, "/");
return accessToken;
} else {
const accessURL = `https://accounts.spotify.com/authorize?client_id=${clientID}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectURI}`;
window.location = accessURL;
}
},
search(term) {
const accessToken = Spotify.getAccessToken();
console.log(accessToken)
return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`,
{ headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json'
// 'Access-Control-Allow-Header': 'http://localhost:3000',
// Origin: 'https://localhost:3000'
}
})
// var myHeaders = new Headers();
// myHeaders.append("Authorization", "Bearer BQB2p2uHUv19Oi9RZQravwPmPzuKsH7wyeP3ZS5Z3dqzBBcSEqEdiEtLBk4mZmA3LUeG78ETFEjkE9eqwNrNb0rjrmbPJxnx-5SWmLEru-FFt3TiY9A-uL1NJa78LRiHeoa_TD3E9XfA8wBt_nraYecl_A8WAGbCCV41KhkHSQriOpdZDH4H");
// var requestOptions = {
// method: 'GET',
// headers: myHeaders,
// redirect: 'follow'
// };
// fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, requestOptions)
// .then(response => response.text())
// // .then(result => console.log(result))
.then(jsonResponse => {
console.log(jsonResponse)
if(!jsonResponse.track) {
return [];
} else {
return jsonResponse.tracks.items.map(track => ({
id: track.id,
name: track.name,
artist: track.artists[0].name,
uri: track.uri
}))
}
})
.catch(error => console.log('error', error))
},
savePlaylist(name, trackUris) {
if(!name || !trackUris.length) {
return;
}
const accessToken = Spotify.getAccessToken();
const headers = { Authorization: `Bearer ${accessToken}`}
let userId;
return fetch('https://api.spotify.com/v1/me', {headers: headers})
.then(response => {
response.json()
})
.then(jsonResponse => {
userId = jsonResponse.Id
return fetch(`https://api.spotify.com/v1/users/${userId}/playlists`,
{
headers: headers,
method: 'POST',
body: JSON.stringify({ name: name })
})
.then(response => {
response.json()
})
.then(jsonResponse => {
console.log(jsonResponse)
const playlistId = jsonResponse.id
return fetch(`https://api.spotify.com/v1/users/${userId}/playlists/${playlistId}/tracks`, {
headers: headers,
method: 'POST',
body: JSON.stringify({ uris: trackUris })
}
)
})
})
}
};
export default Spotify;
App.js
import React, { Component } from 'react';
import "./App.css";
import SearchBar from './../SearchBar/SearchBar';
import SearchResults from './../SearchResults/SearchResults';
import Playlist from './../Playlist/Playlist';
import Spotify from './../../util/Spotify';
class App extends Component {
constructor(props) {
super(props)
this.state = {
playlistName: 'playlist name',
playlistTracks: [],
searchResults: []
}
this.addTrack = this.addTrack.bind(this)
this.removeTrack = this.removeTrack.bind(this)
this.updatePlaylistName = this.updatePlaylistName.bind(this)
this.savePlaylist = this.savePlaylist.bind(this)
this.search = this.search.bind(this)
}
removeTrack(track) {
let newList = this.state.playlistTracks.filter(track.id)
this.setState({ playlistTracks: newList })
}
addTrack(track) {
if(this.state.playlistTracks.find(savedTrack =>
savedTrack.id === track.id)) {
return;
}
}
updatePlaylistName(name) {
this.setState({ playlistName: name })
}
savePlaylist() {
const trackUris = this.state.playlistTracks.map(track => track.uri)
Spotify.savePlaylist(this.state.playlistName, trackUris)
.then(() => {
this.setState({
playlistName: 'New Playlist',
playlistTracks: []
})
})
}
// componentDidMount() {
// window.addEventListener('load', () => {Spotify.getAccessToken()});
// }
search(term) {
console.log(term)
Spotify.search(term).then(searchResults => {
this.setState({ searchResults: searchResults })
})
}
render() {
return (
<div>
<h1>
Li<span className="highlight">st</span>r
</h1>
<div className="App">
<SearchBar onSearch={this.search}/>
<div className="App-playlist">
<SearchResults
onAdd={this.addTrack}
searchResults={this.state.searchResults}/>
<Playlist
onSave={this.savePlaylist}
onNameChange={this.updatePlaylistName}
onRemove={this.removeTrack}
playlistName={this.state.playlistName}
playlistTracks={this.state.playlistTracks}/>
</div>
</div>
</div>
)
}
}
export default App;