graem
graem

Reputation: 75

React proxy to express backend not working

My problem is that I have a create-react-app setup in a client folder and I need to connect it to a backend which I am using express for. The express server is running on localhost:3001, so in the client's package.json I have "proxy": "http://localhost:3001".

client/package.json:

{
    ...
    "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject"
    },
    "proxy": "http://localhost:3001",
    ...
}

And when I try making a simple fetch to the server, I get CORS blocked, despite the server acknowledging that the request was hit.

server/index.ts:

app.get('/api', (req, res) => {
    console.log("Received");
    res.send("Received");
});

Note that the server console logs "Received"

client/App.tsx:

async function onclick () {
    await fetch('http://localhost:3001/api')
        .then((x: Response) => {
            console.log(x);
        })
        .catch((e: Error) => {
            console.log(e);
        });
}

The console log shows e was 'TypeError: failed to fetch'

Any help with this would be greatly appreciated. I have checked other threads and tried their solution of deleting package-lock and node_modules many times now but with no luck.

Upvotes: 1

Views: 1474

Answers (1)

aleksxor
aleksxor

Reputation: 8340

When you're fetching http://localhost:3001/api you're trying to fetch the data directly from your node server. The request is cosidered CORS as the ports of the request origin and request destination are different: 3000 != 3001. While the proxy server works on the same domain and port your create-react-app is served from (http://localhost:3000 in your case).

Change the request url to make requests to the proxy itself and you're good:

  ...
await fetch('/api')
  ...

Or include and config cors express middleware to allow requests from localhost:3000 or other trusted origins as a more advanced solution.

Upvotes: 1

Related Questions