0

i'm facing the issue that when i set header i'm unable to send the token to the API.one more strange issue is that when i see in my network log, i can see method getting converted to 'OPTION', also my 'Token' is not being sent. see below Error :

enter image description here

i have tried to find out all the ways but nothing worked for me, can anyone help here.

Reffered questions :

Using http rest apis with angular 2

Angular2 OPTIONS method sent when asking for http.GET

My code :


//set token for Authorization

  setHeaders() {
    var token = this.localStorageService.getToken();
    let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
    headers.append('Authorization', token);
    this.options = new RequestOptions({ headers: headers });
  }

//function
getMaintenanceType() {
    this.setHeaders();
    return this.http.get(this.url_Configuration.maintenancetype, this.options)
      .map(res => res.json())
  }
Ayushi Tomar
  • 235
  • 1
  • 3
  • 17
  • why are you still using classes from `@angular/http` module, which is **deprecated**. Instead you should use classes from `@angular/common/http`. – Ankur Shah Dec 01 '17 at 05:52

2 Answers2

0

Please try to use below solution, it will work.

Set Header with the request :

Create a method setHeader :

 setHeader(): RequestOptions {
    let headers = new Headers()
    headers.append('Accept', 'application/json');
    headers.append("X-Auth-Token", this.accesToken);
    let options = new RequestOptions({ headers: headers });
    return options;
}

And then Use it :

this.http.get(this.baseURL + url, this.setHeader()).map(res => res.json());
Mohit Saxena
  • 1,439
  • 1
  • 12
  • 21
0

I see that you are having Error Code 403. By Any chance, is your server running on a different platform like 'apache, JBOSS, ... etc' and your UI application is on different. If that is the case, You need to implement CORS support to your server, and I can help you with it, once you confirm the server environment.

As of now, I see a couple of things that can be changed in your code, for starters, and this might help too:

headers ;
headers = new Headers ({ 'Content-Type': 'application/json' });
this.headers.append('Accept', 'application/json');
this.headers.append("X-Auth-Token", this.accesToken);
let options = new RequestOptions({ headers: headers, method: 'get' });
Rahul
  • 121
  • 1
  • 2
  • 10
  • You need to pass the options as method: 'get' – Rahul Dec 01 '17 at 08:52
  • i tried your code too but it is still not working, strange thing is that my code is working for few APIs but not for some.. in those some APIs which are not working i have tried everything but it is not working :( – Ayushi Tomar Dec 01 '17 at 09:27
  • Well in that case, Can you share the server get code?? Also where is your server code running, is it in some other environment?? – Rahul Dec 01 '17 at 09:34
  • we have implemented CORS support to our server – Ayushi Tomar Dec 01 '17 at 10:08