React+ASP.NET.Core : No 'Access-Control-Allow-Origin' header is present on the requested resource

≯℡__Kan透↙ 提交于 2020-01-21 00:30:27

问题


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.


回答1:


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.




回答2:


After two difficult days finally I found out how can I fix my problem. Actually one of your comment was a nice clue for me.

@kirk-larkin said:

The response had HTTP status code 500 is key here. When there's an exception in your ASP.NET Core project, the CORS headers are cleared. You should try and find out why an exception is being thrown.

I traced my code many times, then i found out I forget to register a service which I used in my controller in Startup.cs.

I called these below code in Startup.cs and my problem solved.

services.AddScoped<IMessageService, MessageService>();



回答3:


With ASP.NET Core 2.1, when the controller throws an exception, which results in an error 500, the CORS headers are not sent. This should be fixed in the next version but until then you could use a middleware to fix this.

see

  • https://github.com/aspnet/CORS/issues/90#issuecomment-348323102
  • https://github.com/aspnet/AspNetCore/issues/2378
  • https://github.com/aspnet/CORS/issues/46

Also note that with credentials you need to explicitly add WithOrigins with host and port since most browsers simply ignore it otherwise (see https://stackoverflow.com/a/19744754/2477619):

  app.UseCors(builder =>
    builder
      .WithOrigins("http://localhost:4200")
      .AllowAnyHeader()
      .AllowAnyMethod()
      .AllowCredentials()
  );



回答4:


I had the same problem when I was making my app. I downloaded this chrome extension and the problem was gone. Maybe it helps for you?

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi



来源:https://stackoverflow.com/questions/52896068/reactasp-net-core-no-access-control-allow-origin-header-is-present-on-the-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!