3

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).
2
  • Have a look at your network headers from your web app and api requests. If you're not seeing Access-Control-Allow-Origin: * then you'll want to take a second look at your configuration. The proxy approach described in Arm's answer is a nice workaround that avoids having to tweak the network headers, which is an unsafe approach for production environments. Commented May 11, 2020 at 16:35
  • and fwiw, the Access-Control-Allow-Origin is a response headers, not a request header, so including it in your fetch is not needed (it won't have any effect). Commented May 11, 2020 at 16:36

2 Answers 2

1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

this actually ended up being what i needed to do so i could at least proceed. ill let an actual developer figure out a production approach when we need to :)
1

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

1 Comment

If you use the proxy method, he'll need to change his fetch URL to point to the (presumably node) server running his web app instead of the (presumably IIS express) server running his API as well as tweak the URL path to include the proxy subfolder (ie: /api in your example).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.