Connect Your Express and React Applications Using axios
Bring your front end and back end together
Searching for a way to connect your client-side React application to a server-side Express application? Search no more!
We will be bridging the gap between the front end and the back end using a simple axios request.
This tutorial is going to assume you already have Node.js installed. If not, I created the following tutorial to help guide you through that process: My Node.js Environment Setup. You will only need up to the Node.js part as a prerequisite for this tutorial.
Let’s start at the beginning.
Connect a React front-end application with an Express back-end application through an axios API request
We will be using the following tools to help us achieve our objective:
- React — The front-end library we will be using for this tutorial. Create-react-app allows us to get up and running very quickly.
- Express.js — A framework for Node.js used for building web applications and APIs.
- Axios — An npm library. A promise-based HTTP client for the browser and Node.js.
- CORS — An npm library. An Express middleware that is used to enable Cross-Origin Resource Sharing.
Creating the Back End
We are going to create a new directory to house our entire project. Let’s call it
cd connect-tutorial where we will initialize our node server. Use the following command:
Feel free to accept the default for all of the different questions they ask you.
cors now. We will need to add
cors to allow our axios request to go through from the front end to the back end.
npm i --save express cors
And add our
server.js file with:
Let’s add the following code to
server.js. This is the absolute bare minimum we need to activate an Express server with CORS (Cross-Origin Resource Sharing) enabled:
If you go to localhost:5000 after running
node server.js, you should see this JSON:
Now, let’s get that to appear in the console of our React application.
Setting Up Our Front End
Let us now create our React application inside of our
connect-tutorial directory. Hit
Ctrl-c to terminate the back-end server. We are just going to name our React project
npx create-react-app client
cd client where we are going to install a module to help us make an API request:
npm i --save axios
Now, let’s add the following code to
App.js. Most of this is React boilerplate code. You only need to worry about adding the axios request:
npm start inside of your
client folder and
node server.js inside of your
This message will now appear in your console. The same message we saw before but now on the client-side server.
Easy does it! We have connected our front-end React app to our back-end Express app.
If you have any questions, comments, or concerns, please let me know in the comments section.