When building a full-stack React and Node.js application, the frontend (React) needs to communicate with the backend (Node.js + Express) to fetch or send data. Axios, a popular JavaScript library, makes this process efficient with its powerful HTTP request capabilities.
In this guide, we will walk through step-by-step instructions to connect a React frontend to a Node.js backend using Axios for API requests.
Create a new backend folder and initialize a Node.js project:
mkdir backend
cd backend
npm init -y
2. Install Express and CORS:
npm install express cors
Inside the backend
folder, create a file called server.js
and add the following code:
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors()); // Allow requests from frontend
app.use(express.json()); // Parse JSON requests
// Sample API endpoint
app.get("/api/message", (req, res) => {
res.json({ message: "Hello from the backend!" });
});
// Start the server
const PORT = 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Start the backend server
node server.js
In a separate directory, create a new React project:
npx create-react-app frontend
cd frontend
Axios is used to send API requests:
npm install axios
Inside the React app, open src/App.js
and replace the code with the following:
import React, { useState, useEffect } from "react";
import axios from "axios";
const App = () => {
const [message, setMessage] = useState("");
useEffect(() => {
axios.get("http://localhost:5000/api/message")
.then(response => setMessage(response.data.message))
.catch(error => console.error("Error fetching data:", error));
}, []);
return (
<div>
<h1>React Frontend Connected to Node.js Backend</h1>
<p>Message from Backend: {message}</p>
</div>
);
};
export default App;
Start the React development server:
npm start
Modify server.js
to include a POST route:
app.post("/api/message", (req, res) => {
const { text } = req.body;
res.json({ message: `Received: ${text}` });
});
Modify src/App.js
to include a form for sending data:
import React, { useState, useEffect } from "react";
import axios from "axios";
const App = () => {
const [message, setMessage] = useState("");
const [inputText, setInputText] = useState("");
useEffect(() => {
axios.get("http://localhost:5000/api/message")
.then(response => setMessage(response.data.message))
.catch(error => console.error("Error fetching data:", error));
}, []);
const sendMessage = () => {
axios.post("http://localhost:5000/api/message", { text: inputText })
.then(response => setMessage(response.data.message))
.catch(error => console.error("Error sending data:", error));
};
return (
<div>
<h1>React Frontend Connected to Node.js Backend</h1>
<p>Message from Backend: {message}</p>
<input
type="text"
value={inputText}
onChange={(e) => setInputText(e.target.value)}
/>
<button onClick={sendMessage}>Send</button>
</div>
);
};
export default App;
Once your application is working locally, you can deploy it.
App.js
to use the deployed backend URL instead of localhost
.By following this guide, you have successfully connected a React frontend to a Node.js backend using Axios. You have learned how to:
✅ Set up a backend with Node.js and Express
✅ Create API routes for GET and POST requests
✅ Use Axios to fetch and send data
✅ Deploy the application for production
Now, you can build and scale your full-stack applications with React and Node.js! 🚀