'My react app and express server are on different ports

Problem/error: I am running my react app on port 3000 and express on 3001.

error: Access to fetch at 'http://localhost:3001/api' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

//react code 
//this function gets called when a button get pressed
...
post = () => {
  const client_data = {info: this.state.input};
  const options = {
    method: "POST",
    headers: {
      "Content-Type": "application/json
    },
    
    body: JSON.stringify(client_data)
  }

  fetch("http://localhost:3001/api", options);
}
...

Server is pretty simple

var express = require('express');
var app = express();

app.post('api', (request, response)=>{console.log(request})

(when I add "app.listen(3000)" react stops working)



Solution 1:[1]

You have to proxy your requests from react to express. The best way is to let it do your WebPack devServer, having this configuration:

(I assume, your express server is on 3000 and your React app on 3001)

devServer: {
    ...
    ...
    proxy: {
      '/api': {
        target: 'http://127.0.0.1:3000/',
      },
    },

This says, that whichever request to path /api will be redirected to port 3001. Then you fetch to

fetch("/api", options); 

Client automatically requests localhost:3001 (port on which the application is running), but the proxy redirects to 3000.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fide