Search code examples
reactjsiisasp.net-core-webapinpm-run

React build causes CORS error when there were no issues in development


I have built a React application (my first React application), and a C#.NET Core 3.1 Web API which serves data to the UI. I am deploying the API and the React application on the same server (Windows 10) with port 3030 for the API and port 3029 for the React build which was generated running the command "npm run build". The IIS site for the UI was pointed at the build directory.

In my development environment, running the application using the deployed API works and no proxy is needed. When deployed, my screen loads but no records are retrieved via the FETCH and instead there is a CORS error:

Access to fetch at 'http://localhost:3030/api/checking' from origin 'http://localhost:3029' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Why does this work when running out React in development out of Visual Studio Code with a hot load and why does this not work after the deployment? More importantly, how do I get this to work?

API code from Startup.cs

ConfigureServices method

services.AddCors(options => {
    options.AddDefaultPolicy(builder => {
        builder.WithOrigins(Configuration["AppSettings:CorsUrl"])
        .AllowAnyHeader()
        .AllowAnyMethod();
    });
});

Configure method

app.UseCors();

AppSettings.js code

  "AppSettings": {
    "CorsUrl": "http://localhost:3029"
  }

React

I am storing my url within an .env file at the root level as shown below.

REACT_APP_API_URL=http://localhost:3030/api/checking

React Fetch command

In my checking.js component, the data is loaded and a FETCH is performed.

const SERVER_URL=`${process.env.REACT_APP_API_URL}`

function Checking() {
  const [rowData, setRowData] = useState([]);
  const [newData, setNewData] = useState(initialState);
  const [displayModal, setModalDisplay] = useState(false);
  const columnDefinitions = Columns();
  const rowDataRef = useRef(rowData);

  useEffect(() => {
    fetch(SERVER_URL)
      .then((response) => response.json())
      .then((rowData) => {
        setRowData(rowData)
        rowDataRef.current = rowData;
      });
  }, []);
.
.
.

Solution

  • It turns out that I noticed a component misbehaving (ag-grid) and that caused me to run npm update. Once that was complete, I redeployed the build and everything is now working. I believe the update 'fixed' the issue.