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.