Error when calling the API from Annular App: "Origin https://localhost:44419 is not allowed by Access-Control-Allow-Origin.".
Question
- when both asp.net app and angular server running on origin (localhost) why do I encounter cross origin restriction ?
- Below is the asp.net code I have and the angular proxy.conf file. I think I have enabled all the settings but still getting the error.
Angular App is running on: http://localhost:44419 Asp.Net App is running on: http://localhost:52703
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(
options=>options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader().SetIsOriginAllowed(origin => true);
})
);
app.UseCors();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
Here is the code on my angular proxy.conf.js file:
const { env } = require('process');
const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :
env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'http://localhost:52703';
const PROXY_CONFIG = [
{
context: [
"/weatherforecast",
],
target: target,
secure: false,
changeOrigin: true,
headers: {
Connection: 'Keep-Alive'
}
}
]
module.exports = PROXY_CONFIG;
CodePudding user response:
it's right but do you use app.UseCors()
after HttpsRedirection
!?
read more about Cors policy in this link
CodePudding user response:
I figured the issue was in proxy.conf.js
file. I had the http url and port mentioned there while the asp.net app was running under https port.
So after I correct the url below the issue seem to have fixed itself and I do not even need any of the app.useCors()
and related settings listed above (the app runs just fine without that, as there is no cross origin access happening here , both asp.net and angular app running on same machine)
const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT} :
env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'https://localhost:7067';