0
I’m trying to figure out how to pass headers
the correct way to instantiate an object HttpHeaders
in the Angular 5. I have the following code:
postApi(body: any, route: string) {
return new Promise((resolve, reject) => {
this.http.post(url_api + route, JSON.stringify(body), this.options)
.subscribe(res => {
resolve(res);
}, (err) => {
console.log(err)
reject(err);
});
});
}
When I try to instantiate the object HttpHeaders
passing an object as specified in documentation. I get a 404 return (Actually the request was made for my API. But for some reason or error it does not recognize the route):
options = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'x-api-key': 'xxxxxxxxxxxxxxxxxxxx'
})
};
However, if I create an empty object and then add my headers with append
. Everything works perfectly and my route is found without any problem:
options = {
headers: new HttpHeaders()
};
postApi(body: any, route: string) {
this.options.headers.append('Content-Type', 'application/json');
this.options.headers.append('x-api-key', `xxxxxxxxxxxxxxxxxxxx`);
...
}
So I’d like to understand if it’s a mistake instantiating an Httpheaders object like this:
options = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'x-api-key': 'xxxxxxxxxxxxxxxxxxxx'
})
};
https://answall.com/questions/285777/angular-5-ionic-3-n%C3%a3o-can-send-hair%C3%a7alhos-em-requisi%C3%A7%C3%b5es-para-api? noredirect=1#comment583430_285777
– DiegoAugusto
I tried and researched for a few days. But the result was: When I use the "append" in the headers console does not show the added properties and everything works. But I don’t get headers in my API. When I use the "set" in the console the headers appear, however my API returns a Page not found 404 error. I’m not sure if the problem is in the API or the angular/Ionic app. But if I make a request using Postman and passing headers, everything works perfectly. As this was taking me a lot of time and effort, I decided to pass my token via the same parameter.
– alan