Jammming Project - Search not working ('blocked by CORS policy' error)

Hi Everyone,

I’ve been stuck in the Jammming project from the React Module for a while now. I was able to authenticate into my Spotify account but the search feature does not work, getting the following error:

Access to fetch at ‘https://api.spotify.com/v1/me/search?type=track&q=Bob’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Request header field authorizarition is not allowed by Access-Control-Allow-Headers in preflight response.

I’ve checked if endpoints are correct and if it retrieves a token - but can’t seem to find a solution for it.

Please, find codes below:

Spotify.js:

let accessToken;
const clientID = 'hidden';
const redirectURI = "http://localhost:3000/";

const Spotify = {
    getAccessToken() {
        console.log('1 got here');
        if (accessToken) {
            // console.log(accessToken);
            return accessToken;
        }
    
        //check for token match;
        const tokenMatch = window.location.href.match(/access_token=([^&]*)/);
        const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);

        if (tokenMatch && expiresInMatch) {
            accessToken = tokenMatch[1];
            const expiresIn = Number(expiresInMatch[1]);
            window.setTimeout(() => accessToken = '', expiresIn * 1000);
            window.history.pushState('Access Token', null, '/');
            // console.log('got in if');
            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();
        let fetchAddress = `https://api.spotify.com/v1/me/search?type=track&q=${term}`;
        console.log(fetchAddress);
        console.log(accessToken);
        return fetch(fetchAddress, 
        {headers: {
            Authorizarition: `Bearer ${accessToken}`}
        }).then(response => {
            return response.json();
        }).then(jsonResponse => {
            if (!jsonResponse.tracks) {
                return [];
            }
            return jsonResponse.tracks.items.map(track => ({
                id: track.id,
                name: track.name,
                artist: track.artist[0].name,
                album: track.album,
                uri: track.uri
            }))
        })
    },
    savePlaylist(playlistName, trackUris) {
        if (!playlistName || !trackUris.length) {
            return;
        } 
        const accessToken = Spotify.getAccessToken();
        const headers  = { Authorizarition : `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({ playlistName: playlistName })
                })
            }).then(response => response.json()).then(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 from 'react';
import './App.css';
import { Playlist } from './../Playlist/Playlist';
import { SearchBar } from './../SearchBar/SearchBar';
import { SearchResults } from './../SearchResults/SearchResults';
import Spotify from '/Users/mateusmotter/Desktop/Coding/Projects/jammming-test2/src/util/Spotify.js';

class App extends React.Component {
  constructor(prop) {
    super(prop);
    this.state = {
      searchResults: [],
      playlistName: 'New Playlist',
      playlistTracks: [] ,
    };
    this.addTracks = this.addTracks.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);
  }

  addTracks(track) {
    let tracks = this.state.playlistTracks;
      if (tracks.find(savedTrack => savedTrack.id === track.id)) {
        return;
      } 
      tracks.push(track);
      this.setState({ playlistTracks: tracks });
  }
  removeTrack(track) {
    let tracks = this.state.playlistTracks;
    tracks = tracks.filter(currentTrack => currentTrack.id !== track.id);

    this.setState({ playlistTracks: tracks });
  }
  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 : []
    })});
  }
  search(term) {
    Spotify.search(term).then(searchResults => {
      this.setState({ searchResults: searchResults })
    });
  }
  render() {
    return (
      <div>
        <h1>Ja<span className="highlight">mmm</span>ing</h1>
        <div className="App">
          <SearchBar onSearch={this.search}/>
          <div className="App-playlist">
            <SearchResults searchResults={this.state.searchResults} onAdd={this.addTracks}/>
            <Playlist playlistName={this.state.playlistName} 
              playlistTracks={this.state.playlistTracks} 
              onRemove={this.removeTrack}
              onNameChange={this.updatePlaylistName}
              onSave={this.savePlaylist}/>
          </div>
        </div>
      </div>
    )
  }
}

export default App;

Thank you in advance!

Was this ever resolved? I’m encountering the same issue.

There’s a typo in “Authorization” : (

If anyone is still stuck on this topic i modified my headers authorization in the search method in Spotify.js to :

const headers = { Authorization: `Bearer ${accessToken}`};
return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, { headers: headers })

kind of like we did in the savePlaylist method :stuck_out_tongue: