0
votes

I am using django rest framework as backend and trying to authenticate request in angular using token in request headers but angular is not sending any header values. I have tried all methods of adding headers to request

test(){
    //var headers = new HttpHeaders();
     //headers.append('Authorization',':Token '+ token);
    let token='Token '+'d7dd1e453bae5086e33243b9adca5b63d2d927fb8';

    const httpOptions = {
      headers: new HttpHeaders({

        'Authorization':'Token d7dd1e453bae5086e33243b9adca5b63d2d927fb8',
        'Content-Type': 'application/json', 
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers':'X-Requested-With'

      })
    };
    console.log(token);
    this.http.get('http://localhost:8003/hello/', httpOptions).subscribe(

      response=>{console.log(response);}

    );
  }

Access-Control-Request-Headers: access-control-allow-headers,access-control-allow-origin,authorization,content-type Access-Control-Request-Method: GET DNT: 1 Origin: http://localhost:4001 Referer: http://localhost:4001/

1
So just to clarify, we're looking at Angular code here right? I don't think your Angular application should be setting up Access-Control-Allow-Origin and Access-Control-Allow-Headers headers. Your server should be returning these upon an OPTIONS or on any GET. Other then that, could you post the actual response from the server your Angular app is retrieving? It seems like you have gotten the CORS headers the wrong way around.Bjorn 'Bjeaurn' S
I have tried without setting Access-Control-Allow-Origin, Access-Control-Allow-Headers. It doesn't workDeepak Gupta
Please try and read the full text I wrote to help you. It's not about removing these two headers, it's about the full response your server gives when you try and send something. The two headers we talked about aren't supposed to be added on the client, but rather on the server. Your server should tell the client it's okay to send an Authorization header. Your server logs will probably say similar.Bjorn 'Bjeaurn' S

1 Answers

0
votes

I faced the same issue during a recent project, managed to solve it by setting Headers like this:

let headers = new HttpHeaders().set('Authorization', 'Token ...')
                               .append('Content-Type', 'application/json')
                               .append('Access-Control-Allow-Origin', '*')
                               .append('Access-Control-Allow-Headers', 'X-Requested-With');

 // now either:
 const httpOptions = { headers: headers };
 this.http.get('http://localhost:8003/hello/', httpOptions);

 // or
 this.http.get('http://localhost:8003/hello/', { headers: headers });

Regards.