Angular 5 - Can't set header for HttpClient

Viewed 28042

I am trying to make a POST call using HttpClient in an Angular 5 project, and I want to set the header:

import { HttpClient, HttpHeaders, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { AuthData }    from './models/auth-data';

@Injectable()
export class AuthService {

    constructor(private http: HttpClient) { }

    auth = (data: AuthData) => {

        var url = "https://.../login";
        var payload = data;
        var headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
        var options =  {
            headers: headers
        };

        this.http.post(url, payload, options).subscribe();
    }
}

For some reason, the Content-Type header does not seem to be in the request I am making.

enter image description here

Why is this?

6 Answers

This worked for me. Instead of append.

let headers = new HttpHeaders({
'Content-Type': 'application/json'
});

If i see correctly, what you're showing us is OPTIONS preflight request (CORS), not actual POST request.

There should be 2 'requests in question'. http method for one should be OPTIONS (the one you showed here, its called preflight cors request) and one actual POST (if server allows it for your client). If host is different than locahost:4200, which i assume is, then you have to enable cors requests on your server for localhost:4200 client.

Try this:

var headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');

Try this too I had the same issue ;)

ng build --production -host=yourDomain.com

The thing is that the project is built on localhost, using node, and keep these default host and port info, you can change it when you are building your project

const httpOptions = {
        headers: new HttpHeaders({
          'Content-Type':  'application/json',
          'id':id
        })
      };          

note: please send the 'id' as 'String', observe the below modification

 const httpOptions = {
        headers: new HttpHeaders({
          'Content-Type':  'application/json',
          'id':id+''
        })
      }; 

it's working fine.

Related