React + Express — Creating the boilerplate
React + Express — Creating the boilerplate
Avanthika Meenakshi
·
Follow
Published in
CloudBoost
·
·
Sep 6, 2017
2 min read
—
Source code of this tutorial is available in: https://github.com/AvanthikaMeenakshi/ReactNodeNew
Facebook’s create-react-app is a great boon to React enthusiasts because you don’t have to scratch your head for configuring Webpack and Babel. Right-away you can clone create-react-app, and can start coding in react.
Now, let’s see how we can connect our ExpressJS backend to this creat-react-app.
The expressive backend:
Let us first create our express application for the backend.
Creating back-end application scaffold
I have made mysql connection in my application, with which I’m going to fetch records in the routes/users.js file.
Using the npm “mysql”, I’m getting results from the database test. You can find the code in app.js
I have also changed the “start” property of package.json. I’m changing the start script from node ./bin/www to node app.js. I’m running my express application in 4000 instead of usual 3000 because create-react-app by default will run in 3000 and I’m avoiding the address in use clash.
HTTP port setting code is in app.js
The reactive front-end:
Like express-generator, create-react-app creates a quick scaffold of react directory structure. Here’s how you can install it.
Inside the created “frontend” folder, you will find package.json. This file has all the dependencies needed for react to run. Here’s where we will do the trick. You need to add “proxy” property in the package.json. To tell the front-end to proxy any unknown requests to your API server, we’re adding the proxy property. The proxy
option supports HTTP, HTTPS and WebSocket connections. I’m pointing to port 4000 as we’re running our express-application in that port.
In simple words, whenever you call something that is not in static routing(HTML/CSS) the frontend will forward the request to the server mentioned in proxy.
That’s it. Your front-end is all set. Do “npm start” to start your frontend. It will run in port 3000. Now we will display the data from express in our react.
Fetching data in react:
I’m tweaking frontend/src/App.js a bit to display the records we fetched from the database in express. As I already explained, the proxy server comes into play here, the fetch API of react is going to utilize it.
This is going to display all the records from your express in your react. You can actually do much more with create-react-app. You can find it on their readme.md! Hot-reloading of components has been implemented in the current build, so you don’t have to worry about implementing it on your own. Happy scripting!