Emu Emu - 2 years ago 133
HTTP Question

Angular2 unable to set HTTP header authorization

I've a service called ProjectService, where the following code exists:

..... # skip codes
getProjects(): Observable<any> {
let url = API.MAIN_URL + '/api/project/';
return this.http.get(url, this.requestHeaders())
.map(this.extractData)
.catch(this.handleErrorObservable);
}

..... # skip codes
requestHeaders(): any {
let headers = new Headers();
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Authorization', 'token ' + localStorage.getItem('token'));
let options = new RequestOptions({headers: headers});
return options;
}


In my ProjectComponent I tried to subscribe the
getProjects()
from
ProjectService
via following code:

ngOnInit() {

this._projectService.getProjects().subscribe(data => {
this.projects = data;
},
error => this.message = this.errorMessage(error._body));

}


The problem is, whenever my
ProjectComponent
loads, my console gives me following error:


Response for preflight has invalid HTTP status code 401


I go to my browsers network panel to see the error, it shows that


"Authentication credentials were not provided."


means that my request doesn't have any authorization token.

I've used the ModHeader plugin. then added the token there like
token eaab49d1dd392bda3fb807f33e1eb296897efc79
in the
Authorization
hash value.

And it works like a charm!

Don't know how to solve the problem.

Emu Emu
Answer Source

Don't laugh, but I'm sure this is the most lame answer of my question above. I just changed the following lines:

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

To this:

const headers = new Headers();
const options = new RequestOptions({headers: headers});

Then It works!

Also, I'm using Http previously, then I switched to HttpClientModule. But of them are working now.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download