Search code examples
angularangular-httpclient

Angular 5 - Can't set header for HttpClient


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?


Solution

  • 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.