1

I am using HttpClient for making request and on each request I am setting headers but when I see the chrome network tab then these headers are not set.

Code

request(url: string, method: string, body?: Object) {
    // debugger;

    const fullUrl: string = this.baseUrl + '/' + url;
    var data: Object = new Object();

    const headers = new HttpHeaders();
    headers.append('Access-Control-Allow-Origin', '*');
    headers.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    headers.append('Access-Control-Allow-Headers', "X-Requested-With, Content-Type");
    headers.append('Authorization', 'Bearer '+this.auth.getToken());
    headers.append('Accept', 'application/json');

    data['headers'] = headers;


    if (body) {
        // debugger;
        data['body'] = body;
    }


    return this.http.request(method, fullUrl, data)
        .map((res: Response) => res)
        .catch((err: Response) => this.onRequestError(err));
}

Image of Network Tab

Chrome Network Tab

Mehmood Ahmad
  • 627
  • 2
  • 5
  • 22

1 Answers1

1

Instead of data['headers'] = headers;

Try

const req = new HttpRequest(method, fullUrl, data, { headers })
return this.http.request(req)
      .map((res: Response) => res)
      .catch((err: Response) => this.onRequestError(err));
nomanbinhussein
  • 282
  • 5
  • 11
  • Comments on my post actually solved this problem but my another question is how can I set multiple headers? the answer of the duplicate question just setting one header but I need to set multiple header. – Mehmood Ahmad Oct 26 '17 at 17:25
  • You can set multiple headers already like you did here. `const headers = new HttpHeaders(); headers.append('Access-Control-Allow-Origin', '*'); headers.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); headers.append('Access-Control-Allow-Headers', "X-Requested-With, Content-Type"); headers.append('Authorization', 'Bearer '+this.auth.getToken()); headers.append('Accept', 'application/json');` It should work. – nomanbinhussein Oct 26 '17 at 20:52
  • append is not working and set is working but a I don'tvknow how to set multiple headers in this. – Mehmood Ahmad Oct 26 '17 at 21:14