How to add headers to my Angular post request?

老子叫甜甜 提交于 2019-12-03 11:08:54

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.

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);
        }
    )
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!