Reputation: 51
First time trying to make an api with asp.net core, I am using ASP.NET Core 3.1. I run into this console error when I try to send a GET request:
Access to XMLHttpRequest at 'https://localhost:5001/api/items/1' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have tried a lot of solutions on this site and from others and they do not seem to be working for me. Here is what I have for my Javascript side:
const sendRequest = async function(url) {
try {
let response = await axios.get(url);
return response;
} catch (error) {
console.error(error);
return [];
}
};
Here is what I have in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowMyOrigin",
builder => builder.WithOrigins(
"http://localhost:8080/")
.WithMethods("POST", "GET", "PUT")
.WithHeaders("*")
);
});
services.AddDbContext<DBContext>(opt =>
opt.UseSqlServer(Configuration.GetConnectionString("DatabaseName")));
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//app.UseAuthentication();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("AllowMyOrigin");
//app.UseAuthorization();
//app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
If this is too little info I will try to clarify, but like I said this is my first time doing something like this that deals with the cors policy.
Upvotes: 1
Views: 815
Reputation: 21
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
}
Upvotes: 1
Reputation: 27815
builder.WithOrigins("http://localhost:8080/")
Please note that the specified URL must not contain a trailing slash (/
). Please modify the code like below, then check if it works well.
services.AddCors(options =>
{
options.AddPolicy("AllowMyOrigin",
builder => builder.WithOrigins(
"http://localhost:8080")
.WithMethods("POST", "GET", "PUT")
.AllowAnyHeader()
);
});
Upvotes: 1