Actually this is not a duplication post,I know a part of the title asked many times in stackoverflow community, I read all posts, and answers, but I think my problem and technologies which I used are different.
First of all I should mention ASP.NET Core WEB/API
is my back-end-app and Reactjs
is my front Application.
I read about CORS
and I found out I must enable CORS
on ASP.NET
App and put 'Access-Control-Allow-Origin':'*'
on my request's header, but I still have the below error while I call an api:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 500. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
This is my Startup.cs
code related to CORS
:
public void ConfigureServices(IServiceCollection services)
{
// other lines of code
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAll"));
});
// other lines of code
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseCors("AllowAll");
app.UseAuthentication();
app.UseMvc();
}
This is my react code:
function save(message) {
const requestOptions = {
method: 'POST',
mode: 'cors',
headers: { ...authHeader(),
'Content-Type': 'application/json',
'Access-Control-Allow-Origin':'*',
},
body: JSON.stringify(message)
};
return fetch(config.apiUrl + '/message/save', requestOptions).then(handleResponse, handleError);
}
Thanks for your responding.
If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.
I had a similar problem recently. In my case it started working when I added services.AddCors();
in my ConfigureServices
method and this part of code
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
in my Configure
method. Remember to add those BEFORE UseMvc() call in both cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With