Angular 5 - Can't set header for HttpClient
Asked Answered
L

6

12

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?

Leopoldoleor answered 17/11, 2017 at 15:47 Comment(8)
Is you request even firing? Have you checked with logs or debug if your headers get set before the request fires? Anyways you should be supposed to return an Observable not a Subscription.Benniebenning
Content-Type doesn't change, what does change mean, change from what to what? :)Slovenia
can you specify, what exactly does it mean that 'header does not seem to be in request'? says who? devtools in browser? or server endpoint? or?Multipartite
Yes, the developer tools. I have updated the question with a sample.Leopoldoleor
if i see correctly, what you're showing us is OPTIONS preflight request (CORS), not actual POST requestMultipartite
What I did is 1) open "Chrome developer tools" 2) Check the "network" tab 3) Click the request in question 4) Check the "headers" tab, which is what I pasted you guys. If I should be looking somewhere else, could you tell me where?Leopoldoleor
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). you might benefit from reading about cors. 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.Multipartite
Ok, this was the right answer. I need to activate CORS on the server. The reason why I was not getting before the second request was because I wasnt getting a 404 code. Post it as a solution and I will accept it. Thanks!Leopoldoleor
M
5

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.

Multipartite answered 18/11, 2017 at 6:22 Comment(1)
What if it is set for 'Access-Control-Allow-Origin' : '*', but still gets preflight request ?Ailsa
J
9

This worked for me. Instead of append.

let headers = new HttpHeaders({
'Content-Type': 'application/json'
});
Jacklight answered 13/5, 2018 at 8:52 Comment(0)
C
6

because HttpHeaders is immutable we have to assign it

const _headers = new HttpHeaders();
const headers = _headers.append('Content-Type', 'application/json')
                        .append('...', '...')
                        .append('...', '...');
Cuvette answered 1/3, 2018 at 18:54 Comment(1)
this is the best answerExtensity
M
5

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.

Multipartite answered 18/11, 2017 at 6:22 Comment(1)
What if it is set for 'Access-Control-Allow-Origin' : '*', but still gets preflight request ?Ailsa
G
-1

Try this:

var headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
Guanidine answered 17/11, 2017 at 17:38 Comment(2)
One reason this won't work is that headers is immutable. You need to assign the result of the append method (which makes a clone of the headers) back to the headers: headers = headers.append(blah)Devlen
headers = headers.append('Content-Type', 'application/json');Jauregui
X
-1

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

Xylene answered 18/11, 2017 at 15:17 Comment(0)
O
-3
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.

Oocyte answered 30/8, 2018 at 9:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.