Deepak Gupta
Deepak Gupta

Reputation: 259

Angular not sending request header values

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/

Upvotes: 0

Views: 583

Answers (1)

Stöger
Stöger

Reputation: 155

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.

Upvotes: 0

Related Questions