Siavash
Siavash

Reputation: 3009

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

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.

Upvotes: 19

Views: 23401

Answers (4)

William Carpenter
William Carpenter

Reputation: 1

As said by @Siavash the fact that it is returning 500 may indicate there is an issue with the build. I was having this problem today as it was working fine on localhost but was failing when deployed.

To debug the error, find this line in your web.config file in the root of the IIS directory:

<aspNetCore processPath="dotnet" arguments=".\CarpetrightBackend.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />

Change stdoutLogEnabled="false" to true and then you will be able to see the error in the log file generated.

In my case I forgot to incude some static csv files when deploying that the program needed to reference and return data from it.

Upvotes: 0

Siavash
Siavash

Reputation: 3009

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>();

Upvotes: 9

Felix K.
Felix K.

Reputation: 15663

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

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()
  );

Upvotes: 5

newbie
newbie

Reputation: 220

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.

Upvotes: 21

Related Questions