简体   繁体   中英

Getting CORS error in ReactJS app when attempting to execute localhost API

I'm attempting to create a simple app to do some AES encryption (required for work). I created a small app in ReactJS that has a textbox for the plain text, a button that calls the encrypt method, and then a readonly textbox that displays the encrypted value.

The encrypt method calls an API that I wrote with ASP.NET Core (lives locally for now) to test the encryption out. The API successfully encrypts and returns the encrypted value when I execute in Postman and/or the browser but when I do it through my React app it throws the CORS error.

I'm extremely new at both creating API's and React so apologies in advance if the fix is a very simple one.

Here is my Startup class in the API project:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();
        services.AddControllers();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseCors(
            options => options.WithOrigins("https://localhost:5001/encryption/encrypt").AllowAnyMethod()
        );

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

    }
}

And then here is my encrypt method in the React app:

encrypt() {
var plainText = this.textToEncrypt.value;
console.log(plainText);

var requestOptions = {
  method: 'GET',
  headers: {
    'Access-Control-Allow-Origin' : '*'
  }
};

fetch("https://localhost:5001/encryption/encrypt?plainText=" + plainText, requestOptions)
  .then(response => response.text())
  .then(data => this.setState({ encryptedText: data.value }))
  // .then(result => console.log(result))
  .catch(error => console.log('error', error));
}

Here's the error from the browser console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:5001/encryption/encrypt?plainText=sample%20text. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

I don't know do we have the same CORS problem, but once I solved that problem with these changes: Adding this line in package.json file:

"proxy": "http(s)://backend.url/api",

And/or by disabling host checking in .env file:

DANGEROUSLY_DISABLE_HOST_CHECK=true

This is not a perfect approach in that this absolutely is not how you want to address the issue in a production environment, but for development purposes you could try this.

if (env.IsDevelopment())
{
    app.UseCors(
        options => options.WithOrigins("*").AllowAnyMethod()
    );
}

This would be in place of your current UseCors implementation. The problem with your current implementation is that (if properly syntaxed) would only allow CORS from itself. You need to allow CORS from the source of your node server (or whatever domain/port is running your web app). Since you do not indicate that in your post, * covers everything (very unsafe, as a reminder, for production).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM