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:
http://wapl8.ad.uclp:9091
http://skw.uat.ad.uclp
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:
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();
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