Issue
I'm developing an Angular application and facing a CORS issue when making POST requests to my server, but only after deploying it on IIS. The application works perfectly on localhost. Here are the details:
Environment:
- Frontend: Angular
- Backend: Node.js, .NET,
- Server URL (IIS):
http://wapl8.ad.uclp:9091
- Angular App URL (IIS):
http://skw.uat.ad.uclp
- Localhost works fine for all requests
Problem: When I try to send a POST request from the Angular app (deployed on IIS) to the server, I encounter the following CORS error:
Access to XMLHttpRequest at 'http://wapl8.ad.uclp:9091/api/YPTApi/Save' from origin 'http://skw.uat.ad.uclp' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
What I've Tried:
- GET requests work fine.
- On my local development environment (localhost), both GET and POST requests work without any CORS issues.
- I've checked Angular's CORS documentation and tried various solutions, but the issue persists after deployment on IIS.
Can anyone help me understand how to configure my environment to allow POST requests without violating CORS rules? Is this an issue with the backend server configuration, or is there something I can do on the Angular side to fix this?
Code:
public static void Configure(IServiceCollection services)
{
const string myAllowSpecificOrigins = "AllowSpecificOrigins";
services.AddCors(options =>
{
options.AddPolicy(name: myAllowSpecificOrigins,
// builder =>
// {
builder =>
{
builder
.WithOrigins(
"https://localhost:44498",
"http://localhost:1285",
"https://localhost:44337",
"http://localhost:44337",
"http://skw.uat.ad.uclp",
"http://skw.ad.uclp"
)
.AllowAnyHeader()
//.AllowAnyMethod()
.WithMethods("GET", "POST", "DELETE", "PUT", "OPTIONS")
.AllowCredentials();
Solution
I don't know if you had configured, but .NET need to set a confogiratin to manage CORS. Add the follow in your Startup ConfigureServices method:
services.AddCors(options =>
{
options.AddPolicy(name: "general",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod().
AllowAnyHeader();
});
options.AddPolicy(name: "restrictive",
builder =>
{
builder.WithOrigins("http://Your frontEnd URL").
WithMethods("GET", "POST", "PUT", "DELETE")
.AllowAnyHeader();
});
});
Now in Startup, in Configure Method add:
app.UseCors("[general/restritive]; // or whatever name you use...
Is this example, "general" CORS configuration allows any origin from any host, and "restrictive" allows request just from the host you set
Answered By - Stalky
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.