APIs between Node and React with MySQL

React & Node API Blog

Making API Calls Between a Node.js Server and a React App

Building a full-stack app means connecting your React frontend with a Node.js backend. In this guide, you'll learn how to set up a simple Express API and call it from React using fetch, with both GET and POST methods.

📁 Folder Structure

fullstack-app/
├── backend/
│   └── index.js
├── frontend/
│   └── src/
│       └── App.js

🛠️ Backend (Node + Express)

Create this file:

📄 backend/index.js


// Import required modules
const express = require('express');
const cors = require('cors');

const app = express();
const PORT = 5000;

app.use(cors()); // Allow requests from frontend
app.use(express.json()); // Parse JSON bodies

// GET endpoint
app.get('/api/greet', (req, res) => {
  res.json({ message: 'Hello from Node.js backend!' });
});

// POST endpoint
app.post('/api/echo', (req, res) => {
  res.json({ received: req.body });
});

// Start server
app.listen(PORT, () => {
  console.log(`Backend running at http://localhost:${PORT}`);
});
    

Run the backend:

cd backend
npm init -y
npm install express cors
node index.js

⚛️ React Frontend

Create this file in your React app:

📄 frontend/src/App.js


import React, { useState, useEffect } from 'react';

function App() {
  const [greeting, setGreeting] = useState('');
  const [echoResponse, setEchoResponse] = useState(null);

  useEffect(() => {
    fetch('http://localhost:5000/api/greet')
      .then(res => res.json())
      .then(data => setGreeting(data.message));
  }, []);

  const sendData = () => {
    fetch('http://localhost:5000/api/echo', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name: 'Champak Roy', role: 'Developer' })
    })
      .then(res => res.json())
      .then(data => setEchoResponse(data));
  };

  return (
    <div>
      <h2>React & Node API Demo</h2>
      <p>GET: {greeting}</p>
      <button onClick={sendData}>Send POST Request</button>
      {echoResponse && (
        <pre>{JSON.stringify(echoResponse, null, 2)}</pre>
      )}
    </div>
  );
}

export default App;
    

Run the frontend:

npx create-react-app frontend
cd frontend
npm start

🛡️ Fixing CORS

Make sure this line is present in your Node server:

app.use(cors());

✅ Test the Setup

  • Start backend: node index.js
  • Start frontend: npm start
  • Visit http://localhost:3000
  • See the greeting from the backend
  • Click the button to send data to backend via POST

📌 Summary

  • Backend with Express handles GET and POST
  • Frontend uses fetch API
  • CORS enabled to allow cross-origin requests

Post a Comment

0 Comments

Me