Having your frontend and backend in two separate repositories rather than combining both is a common enough pattern. Follow the steps below to connect your React project that is running on port 3000 with your Express server that is running on port 4000.
1. Add a proxy in your frontend
In your React app, open up package.json
and add the following line anywhere:
// React app, package.json
"proxy": "http://localhost:4000"
This will let your React app know that when you do fetches that look like they're for resources on the same server, for example fetch('/')
, it will look for that endpoint on the proxy server you specified, i.e. your Express server.
2. Add an API endpoint
Add an example endpoint:
// Express repo, app.js
app.get("/hello", (req, res) => res.send("Hello World!"));
And an example fetch request:
// React repo, src/App.js
useEffect(() => {
const fetchResource = async () => {
const response = await fetch("/hello");
const responseVal = await response.text();
console.log(responseVal);
};
fetchResource();
}, []);
3. Try it out!
Start up both servers in localhost. Again, your React app will run on port 3000 and your Express server will be on port 4000.
Since the fetch
method is wrapped in a useEffect
, it will run as soon as the React server starts and the page is rendered. You can now open up the console in the frontend and see that the pinged endpoint's response is being logged correctly.
Common issues
If you see "You need to enable JavaScript to run this app" as a response, chances are you forgot to add the proxy in
package.json
.If the browser network tab shows that the url specified in the
fetch
doesn't exist (a 404 error), try replacing localhost with 127.0.0.1 as the proxy value.If it's anything else, write it down in the comments.
Thanks for reading! Until next time 👋
Cover photo by Hans-Peter Gauster on Unsplash
Top comments (0)