If you want to connect your client-side React app with your server-side Express app then you can use axios to do so! This tutorial assumes that you already have node.js installed.
So without further ado, let's begin the tutorial.
🎯Target
Connect a React front-end application with an Express back-end application through an axios API request.
⚙️Tools
We will be using the following tools to help us achieve our target:
- 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 back-end
We are going to create a new directory to house our entire project. Let’s call it axios-tutorial
.
mkdir axios-tutorial
Go to the project directory and run,
npm init
Accept all the default questions asked to you,
Now, let's install cors
and express
. 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
Now to activate the express server, create a file called server.js
and add the following code.
require("dotenv").config();
const express = require("express");
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.get("/", (req, res)=>{
res.json({ message: "Hello world" });
});
app.listen(port, ()=>console.log(`Listening on ${port}`));
Run the code by typing node server.js
on the terminal.
🍁Setting up front-end
Let us now create our React application inside of our axios-tutorial
directory. We are just going to name our React project frontend.
npx create-react-app frontend
Now install axios module to make 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:
import React from "react";
import logo from "./logo.svg";
import "./App.css";
import Axios from "axios";
function App() {
Axios({
method: "GET",
url: "http://localhost:5000/",
headers: {
"Content-Type": "application/json"
}
}).then(res => {
console.log(res.data.message);
});
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
Run npm start
inside of your frontend folder and node server.js
inside of your axios-tutorial
directory.
🎊🎉Done. Your backend and frontend are both connected with axios.
🍁Another way to connect frontend to backend
- You can simply add the proxy in
package.json
file of frontend and remove the below code fromapp.js
file but remember to remove the proxy when you are deploying the site.Axios({ method: "GET", url: "http://localhost:5000/", headers: { "Content-Type": "application/json" }
🚀Config Default
You can specify config defaults that will be applied to every request.
Global axios defaults
axios.defaults.baseURL = 'https://api.example.com';
You can change the default baseURL like this way if the request is routing in one port.
Thanks for reading. Feel free to comment down if you are stuck in any process. Sayonara🖐️