reactjsasp.netasp.net-corecorsasp.net-core-webapi

Preflight request from React Client with ASP.NET Core backend blocked by CORS policy


I am working on a simple application with React as the client app and ASP.NET Core as the server. However, when I try sending a POST request from the React client to the ASP.NET Core server, I am encountering this CORS error:

localhost/:1 Access to XMLHttpRequest at 'http://localhost:5094/api/records' from origin 'https://localhost:44477' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

I have already configured CORS in the ASP.NET Core backend in the Program.cs file:

using Microsoft.EntityFrameworkCore;
using Npgsql.EntityFrameworkCore.PostgreSQL;
using NET_REACT.Context;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddCors(o =>
{
    o.AddDefaultPolicy(
        builder =>
        {

          //you can configure your custom policy
            builder.WithOrigins("https://localhost:44477")
            .AllowAnyMethod()
            .AllowAnyHeader();
        });
});

builder.Services.AddControllersWithViews();

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddDbContext<MyDbContext>(
    o => o.UseNpgsql(builder.Configuration.GetConnectionString("MyPostgresConnection"))
);

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();


app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

app.MapFallbackToFile("index.html");

app.Run();

In the React client, I am using Axios to send the POST request as shown in the App.js file:

import React, { useState } from 'react';
import axios from 'axios';

const App = () => {
  const [Name, setName] = useState('');
  const [Email, setEmail] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const response = await axios.post('http://localhost:5094/api/records', { Name, Email });
      console.log(response.data);
    } catch (error) {
      console.error('Error:', error.message);
    }
  };

  return (
    <div>
      <h1>Send POST Request</h1>
      <form onSubmit={handleSubmit}>
        <div>
          <label>Name: </label>
          <input type="text" value={Name} onChange={(e) => setName(e.target.value)} />
        </div>
        <div>
          <label>Email: </label>
          <input type="email" value={Email} onChange={(e) => setEmail(e.target.value)} />
        </div>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

export default App;

I would appreciate any insights or suggestions on how to resolve this CORS issue and successfully send the POST request from my React client to the ASP.NET Core server. Thank you!


Solution

  • Are you sure the URL is correct? It seems wrong because you gave https:// link to cors but react not run https and you gave api to http:// but .net core normally have default SSL can you check it? otherwise allow all ip with this:

    var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
    builder.Services.AddCors(options => options.AddPolicy(name: MyAllowSpecificOrigins,
        policy =>
        {
            policy.AllowAnyOrigin()
                  .AllowAnyMethod()
                  .AllowAnyHeader();
        }
    ));
    app.UseCors(MyAllowSpecificOrigins);