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