How to add headers to my Angular post request?
Asked Answered
C

3

30

For a school project I need to make a simple login page with Angular. When a login button is clicked I need to add an Authorization header with my post. I created a backend and when I post my Authorization value to that backend with postman it works so nothing wrong with the backend. When I try to post to the same backend with my frontend it doesn't work. What is the best way to add headers to your post? It seems that the opinions are divided. This is my code:

export class LoginComponent{
    title = 'Login';
    email = '';
    password = '';
    credentials = '';
    basic = '';
    constructor(private http:HttpClient){

    }

    createAuthorizationHeader(headers:Headers,basic){
        headers.append('Authorization',basic);
    }

    login(event){
        this.email = (<HTMLInputElement>document.getElementById("email")).value;
        this.password = (<HTMLInputElement>document.getElementById("password")).value;
        this.credentials = this.email + ":" + this.password;
        this.basic = "Basic " + btoa(this.credentials);
        console.log(this.basic);
        let headers = new Headers();
        headers.append('Content-Type','application/json');
        headers.append('Authorization',this.basic);
        let options = new RequestOptions({headers:headers});
        console.log(headers);
        return this.http.post('http://localhost:8000/api/v1/authenticate',options)
        .subscribe(
            res =>{
                console.log(res);
            },
            err => {
                console.log(err.message);
            }
        )
    }
}

When I run that code I get a 400 status response and the headers are not added.

Chiarra answered 11/12, 2017 at 16:54 Comment(1)
Possible duplicate of Angular [4.3] Httpclient doesn't send headerTypehigh
H
74

The second argument passed in to HttpClient.post represents the body of the request, but you're providing Headers here. Use the following to provide the headers correctly:

return this.http.post(
    'http://localhost:8000/api/v1/authenticate',
    null,
    options);

I've shown null in the example for the body, but you probably want that to include the email and password properties in some form.

You're also mixing Http and HttpClient. If you're going to use HttpClient (which is now the recommended approach), drop RequestOptions and Headers in favour of HttpHeaders. This becomes:

let headers = new HttpHeaders({
    'Content-Type': 'application/json',
    'Authorization': this.basic });
let options = { headers: headers };

The rest of the code stays the same. Your createAuthorizationHeader function needs to use and return an instance of HttpHeaders. This class is immutable, so append returns a new object each time it is called. Import HttpHeaders from @angular/common/http.

Hubie answered 11/12, 2017 at 17:2 Comment(0)
C
4

This may Help You

let headers = new Headers();
headers.append('Content-Type','application/json');
//post data missing(here you pass email and password)
data= {
"email":email,
"password":password
}
return this.http.post('http://localhost:8000/api/v1/authenticate',data,{ headers: headers})
    .subscribe(
        res =>{
            console.log(res);
        },
        err => {
            console.log(err.message);
        }
    )
Comorin answered 11/12, 2017 at 16:57 Comment(3)
Thanks for the fast reply but already tried this solution and it doesn't work. The headers is still not added.Chiarra
your backend should accet 'Content-Type'Comorin
which technology used in backendComorin
P
1
    const headers = new HttpHeaders().set( 'content-type', 
    'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' 
    ); 
    this.http.post( "/api/images", imageInFormData, 
    {headers:this.headers}).subscribe((response)=>{ 
    console.log(response)}); 
Preacher answered 29/10, 2023 at 17:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.