Reputation: 1496
I have a POST Im performing from Postman, which works perfect, but when Im posting through Angular, Im getting:
[Error] XMLHttpRequest cannot load (DOMAIN) due to access control checks.
After checking several answers here and at Google, I came up with changing web.config and express to enable CORS.
The NODE application is hosted on IIS, and I already added the customHeaders to the web.config:
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
The Angular code is pretty straight forward:
let APIURL = sessionStorage.getItem('endPoint') + "outside/login";
let options = { headers: new HttpHeaders().set('Content-Type', 'application/json') };
let body: any = this.payLoad;
this.httpClient.post(APIURL, JSON.stringify(body), options).subscribe(
result => {
.....
.....
.....
})
I also added
app.options('*', cors())
to Express but still get this error.
This worked perfect while I was using the IP address and port 3000 on the remote server. Everything crashed when I set the domain thru IIS and setup the URL Rewrite.
I want to put special emphasis on this: It works PERFECT on Postman, but it crashes through the app (localhost, or at the web server).
Thanks.
UPDATE: When stopping PM2 and stopping the IIS website, of course Postman does not work, but Angular retrieves the same error, so I tend to thing the problem is at an Angular level (?).
Here's the rewrite rule at IIS
<rewrite>
<rules>
<rule name="ReverseProxyInboundRule1" stopProcessing="true">
<match url="(.*)" />
<action type="Rewrite" url="http://localhost:3000/{R:1}" />
</rule>
</rules>
</rewrite>
Upvotes: 1
Views: 1536
Reputation: 658
Add this to your js file where you require express. I assume you are requiring CORS. If not:
const cors = require('cors')
then
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
and get rid of the customHeaders at your web.config. You are setting the headers twice.
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
Upvotes: 1