Reputation: 71
I'm making http post request in angular project using angular Http, & i'm getting following error.
Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
but if i make that post request with jquery, i don't get any error, it executes as the way it is needed.
This is jquery code i'm using & it works without any issue.
$(function () {
$.post(
"http://www.anything.com/pdfGenerator/",
{
orientation: "portrait",
paperSize : "letter",
return_url : "true",
htmlContent: `<h1>Hello</h1>`
}
).done(function (data) {
alert("Data Loaded: " + data);
});
});
Here's the Angular code & it doesn't work, i get the above mentioned error.
this.url = "http://www.anything.com/pdfGenerator/";
let body:any = {
orientation: "portrait",
paperSize : "letter",
htmlContent: `<h1>Hello</h1>`,
return_url : "true",
};
this.http.post(this.url, body).
subscribe(res => console.log(res));
I've heard people saying add Content-Type in your Response-Header
on server-side. I mean, why should i add this in response header on server if it is working fine using jquery. if it is working through jquery without doing anything extra, then angular should also run it without showing errors.
What i'm doing wrong? what should i do to make it run in angular without modifying server as jquery is already doing it?
Upvotes: 0
Views: 96
Reputation: 2950
One thing that may be happening is that jQuery is sending a different Content-Type
than angular's $http. That might be down to the defaults, so you can try to update it to match jQuery's (you can inspect the network requests to compare the header being sent and find difference).
In the case, it could be that jQuery defaults to a Content-Type
that your server is expecting whilst angular defaults to something else. To set the content type on angular you can use the following syntax: [1]
this.http.post(this.url, body, { headers: {'Content-Type': 'application/json'} })
I see cases where stringifying the body solves issues like this, wouldn't be able to tell if it's your case in specific as I don't have access to your environment, but you may give it a go:
this.http.post(this.url, JSON.stringify(body))
[1] https://docs.angularjs.org/api/ng/service/$http#post
Upvotes: 0