1
votes

I am trying to learn angular 2 by building a simple spotify app.

But somehow I'm stuck in the authentication process.

My issue is that when I try to send an http post with headers set to https://accounts.spotify.com/api/token

let tokenUrl = 'https://accounts.spotify.com/api/token';

    let keyEncrypted = btoa( this.client_id + ':' + this.client_secret);

    let authHeaders = new Headers();
    authHeaders.append('Content-Type', 'application/x-www-form-urlencoded');
    authHeaders.append('Authentication', 'Basic ' + keyEncrypted);

    let options = new RequestOptions({headers: authHeaders});

    let body = 'code=' + authCode + '&grant_type=authorization_code' + '&redirect_uri=' + this.redirect_uri;

    let jsonString = JSON.stringify({
      code: authCode,
      grant_type: 'authorization_code',
      redirect_uri: this.redirect_uri
    })


    return this._http
        .post(
          tokenUrl, 
          jsonString,
          options
          ).map( res => {
            res.json();
          })

I get a pre-flight "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin'..."

But when I remove the headers from the return like

return this._http
        .post(
          tokenUrl, 
          jsonString // Header removed
          ).map( res => {
            res.json();
          })

The pre-flight check seems to have been bypassed but then I get a media type not allowed error.

so I'm confused right now and would like to know: 1. Why does sending post w/o headers bypass the pre-flight check and sending post w/ headers doesn't? 2. Does angular http post send different type of requests when headers are set and aren't set?

Many Thanks.

2
You are using localhost to access to your angular app? It's a common practice for services like spotify to let you use a domain from where the requests can come and "localhost" while you are in development mode.dlcardozo

2 Answers

0
votes

You have to understand exactly how you are supposed to get the token from Spotify. But looking at your code, I can tell you from looking at the Spotify documentation this line

authHeaders.append('Authentication', 'Basic ' + keyEncrypted);

should probably be

authHeaders.append('Authentication', 'Bearer ' + keyEncrypted);

First, try and get a token from the Spotify API using a program like Postman or Curl, making requests with the token, and then once you have received data from the API and you have a clear understanding of how the flow should work, then try with Angular2 application.

0
votes

Here - a text/plain header doesn't trigger a CORS pre-flight. Removing the content-type header will default to text/plain.

Try using Chrome and launching it in unsafe mode - an example in PowerShell would be

& "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:\Users\{yourusername}\AppData\Local\Google\Chrome\User Data\Default"