Overview :
React framework is great for creating awesome web apps and UIs. But sometimes we need extra functionalities like integrating database or performing authentication. Such stuff needs to be done in backend, you don't want that anyone can see your secret keys or hashing stuff in frontend.
That's why in this article we are going to learn how to connect your React frontend with express backend. Sometimes this task get really overwhelming, you might get stuck with CORS issue, we will be handling all of them in this one article.
Our motive is to create a server that host an API and then we make a GET request from React frontend and display the data on screen.
Prerequisites :
- Basic React knowledge and comfortability with environment.
- Basic Express knowledge.
Let's get going π
First of all create a folder and call it anything, we are naming it as app
. This folder will contain all our frontend + backend code.
Now we will start with creating backend first,
Setting up Server
Open the terminal and locate to your app
folder. Now inside this folder we will create server.js
file. Yeah exactly this file will contain code responsible for server running and API hosting.
now we are going to initialize npm
in this folder to handle external packages and dependencies.
In the terminal type npm init -y
it will initialized the npm with default values.
As a result you will see a file with name package.json
will automatically get created.
From this step we are going to handle rest of the things on your favourite code editor. I am using VSCode in this article.
Open app
folder on VSCode.
Now we have to install some packages, these are
express
cors
I hope you are familiar with express
it's a widely used module for maintaining backend. Now what is the use of cors
library, okay so for this first we need to understand what CORS really is.
CORS is shorthand for Cross-Origin Resource Sharing. It is a mechanism to allow or restrict requested resources on a web server depend on where the HTTP request was initiated.
Whenever we make request to a server we send a header called origin
. It contain the information about from where the request is originated and using this header a web server can restrict or allow the resource sharing between client and server.
By default requests from any other origins will be restricted by the browser.
If you want to read more about CORS, here's the link you can refer to More on CORS
Now with the use cors
middleware we can allow CORS for all routes or to some specific routes, in this article we will allow for all routes but if you want to read more then refer to cors documentation.
For installing above packages open terminal in your VSCode and type following npm install express cors
.
Now all left is to setup our backend server, coding time π₯³
Let's start with creating a file data.js
. This file will contain our API data that we are going to host and then we export
the API data so that we can use it inside our server.js
.
Okay now let's setup our server, open the server.js
and follow the below image
As you can see that the code is self explanatory but still I want to highlight a point that is port number on which our server is listening
Take any free port number you want except 3000
why? because port 3000
is used by react frontend and if you use same for your backend then it might gonna crash. Here you can see I used port 5000
.
Now let's test if our server is working or not. Open the terminal again and type following node server.js
and in the console you can see it'll be printing server is running on port 5000
.
Open your browser and go to the following URL http://localhost:5000/api
You can see your API data there in JSON format. For better visualization you can use extensions like JSON viewer pro here's the link for download.
YAYYYY π... Our server is up and running.
Time to move to frontend and start building it.
Setting up React frontend
First of all make a folder client
, this will contain our frontend stuff.
Now go inside the client
folder and type the following on terminal npx create-react-app my_app
It'll take some time to process and when it done you'll see a folder named my_app
created, see below
Now inside the VSCode you can see that client/my_app
will contain some pre-build files they all are the initial setup for React frontend. You can modify them as the way you want, but in this article we just modify package.json
and App.js
to our need.
Now open the package.json
from the client/my_app
folder on VSCode and add the following property below private: true
property.
proxy: "http://localhost:5000"
see below for reference
Now adding this property makes React to use http://localhost:5000
as default URL for making requests.
It's time to setup App.js
to make request to our server and render data on client's screen.
Open App.js
on VSCode and in the function App
delete everything inside the div having class 'App'
and do the following.
As you can see the code is self explanatory but still I again want to highlight a point that, just take a look at the fetch("/api")
. You can notice we are not providing complete endpoint like http://localhost:5000/api
and the reason is we don't need to remember the proxy
property we set earlier. All credit goes to it, now we can create as many routes we want inside your server and can access them in React with similar manner.
Now open terminal inside VSCode and select a new zsh
or bash
whatever you prefer and make sure you are inside themy_app
folder.
and when you are in, type following in terminal to start the React frontend server. npm start
ignore all the warnings for now
This command will basically compile your React code and start the server at port 3000
. It will also automatically open your web browser and get located to http://localhost:3000
and what you can see is a big *" Hello World " * on screen.
Open the Developers tools
inside brower and in console you can see that our API data is logged there successfully.
Now we are sure that our frontend is working properly and data is also fetched without any problem, so it's time to render the data on screen. Open App.js
on VSCode and replace the already written code with the highlighted part of code.
As you can notice we just replaced the console logging and Hello World to the other code so that it can set the state
value to data array and render it on screen with some styling.
Now just save it and open your browser again to see the final result.
If you want to re-check just modify the data inside data.js
from backend and save it, the modified result will also be displayed on your screen.
YAYYYYYY...... π π₯³ our backend and frontend are now perfectly connected, now you can use your backend for integrating database or authentication without any worries of exposing private data on frontend.
What's next !
If you are still reading, make sure to follow me on Twitter and subscribe to my newsletter for more as I have some exciting stuff coming up every weekend. See Y'all next time and stay safe ^^ π»
Top comments (5)
Great article, though I would suggest not using the index of the map callback function as the key when rendering the divs from the state data. This can cause problems if you start adding or removing data. Try putting an 'ID' property on each object in the data and use that for they key.
yes absolutely, this tutorial is more focussed on how you can integrate and also assuming reader to have some basic react knowledge.
That's why I tried to make things as simple as they can be, ideally one must should not use index for keys
during working with react-router-dom or sometimes normally data fetching or posting, if anyone of you gets this error:
" Unexpected token < in JSON at position 0 "
then don't panic if you followed the tutorial well and still seeing this, It's just a cache issue
Solution:
Delete the package-lock.json file and node_modules folder then run " npm install " to again install then
Now run your server again and the error will be gone π
Great article!
great article!