Contents

Fixing a Server-Side CORS Issue in React Development Mode

Contents

Fixing a Server-Side CORS Issue in React Development Mode

Background

Recently I was building a backend proxy service for openai — an account pool for a backend pool that buffers completion requests coming from the front end.

The backend was basically done, so I needed a demo front end for testing and demonstration. I used react to build a simple chat front end; most of the code was generated by GPT-4 over several rounds and stitched together. Since I had never written react, it took me a while to pick and stitch the pieces, because CHATGPT also makes mistakes — obvious to anyone who knows, but easy to fall for if you don’t.

Once the program ran, because the interface the backend gives the front end is a websocket, it threw on startup: Access to XMLHttpRequest at 'http://localhost:3014/socket.io/?EIO=4&transport=polling&t=OSYSDmI' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Solution

After some research, the CORS problem actually has to be solved on the SERVER side. First, my SERVER side uses Nestjs and the websocket uses WebSocketGateway, defined as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@WebSocketGateway({
  cors: {
    origin: '*',
  },
  namespace: 'main',
})
export class WSGateway
  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
  	...
  }

websockeet already has CORS added, so it should not be that. The problem is at localhost:3000 — this is the web service the front-end react uses, and the error is from that 3000. After looking it up, in development mode react-scripts uses webpack’s dev server. Per the official docs:

Create a new scr/setupProxy.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const { createProxyMiddleware } = require("http-proxy-middleware");

module.exports = function (app) {
  app.use(
    "/",
    createProxyMiddleware({
      target: "http://localhost:3014", // Replace with the API server URL
      //   changeOrigin: true,
      ws: true,
      logger: console,
      //   pathRewrite: {
      //     "^/api": "", // Remove the '/api' prefix from the request URL
      //   },
    })
  );
};

Set target to the address of the target server react wants to connect to, and set ws to true.