Skip to main content

How to Connect Frontend to Backend Using POST Request (JavaScript + Node.js)

 

How to Connect Backend to Frontend: A Complete Guide with POST Request Example

In modern web development, building a full-stack application means handling both frontend and backend. The frontend is what users interact with—buttons, forms, and visuals. The backend handles data, logic, and connections with databases.

This guide will walk you through how to connect your backend and frontend, specifically focusing on making a POST request from the frontend to the backend using JavaScript and Node.js with Express.




What Is a POST Request?

POST request is one of the HTTP methods used to send data to a server. For example, when you submit a login form, your email and password are sent using a POST request to the backend for verification.


Basic Setup: Tools You'll Need

  • Frontend: HTML, JavaScript

  • Backend: Node.js, Express.js

  • Database (optional): MongoDB (with Mongoose)

  • Postman (optional): For testing APIs

  • VS Code or any code editor


Project Structure

pgsql
fullstack-post-app/ ├── backend/ │ ├── server.js │ └── db.js ├── frontend/ │ └── index.html ├── package.json

Step 1: Setting Up the Backend (Node.js + Express)

1.1 Initialize Node Project

Open your terminal and run:

bash
mkdir fullstack-post-app cd fullstack-post-app mkdir backend npm init -y npm install express body-parser cors mongoose

1.2 Create server.js

Inside backend/, create a file called server.js:

js
const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const app = express(); const PORT = 5000; // Middleware app.use(cors()); app.use(bodyParser.json()); // POST Route app.post('/api/data', (req, res) => { const { name, email } = req.body; console.log('Data received:', name, email); res.status(200).json({ message: 'Data received successfully', data: { name, email } }); }); // Start server app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });

This simple server listens for a POST request at /api/data.


Step 2: Setting Up the Frontend

2.1 Create index.html

Create a folder called frontend/ and a file index.html inside it:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <title>Frontend POST Example</title> </head> <body> <h1>Send Data to Backend</h1> <form id="dataForm"> <input type="text" id="name" placeholder="Enter your name" required /> <input type="email" id="email" placeholder="Enter your email" required /> <button type="submit">Send</button> </form> <p id="response"></p> <script> const form = document.getElementById('dataForm'); form.addEventListener('submit', async (e) => { e.preventDefault(); const name = document.getElementById('name').value; const email = document.getElementById('email').value; try { const response = await fetch('http://localhost:5000/api/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, email }), }); const result = await response.json(); document.getElementById('response').textContent = result.message; } catch (error) { console.error('Error:', error); } }); </script> </body> </html>

This HTML page has a form that sends data to the backend using JavaScript fetch().


Step 3: Connecting Backend to Database (Optional - MongoDB)

Let’s now store the data in a MongoDB database.

3.1 Setup MongoDB

Create db.js in backend/:

js
const mongoose = require('mongoose'); const connectDB = async () => { try { await mongoose.connect('mongodb://127.0.0.1:27017/post_example', { useNewUrlParser: true, useUnifiedTopology: true, }); console.log('MongoDB connected'); } catch (err) { console.error('MongoDB connection error:', err.message); } }; module.exports = connectDB;

3.2 Create Schema and Model

Inside server.js, add:

js
const connectDB = require('./db'); connectDB(); const mongoose = require('mongoose'); const DataSchema = new mongoose.Schema({ name: String, email: String, }); const DataModel = mongoose.model('Data', DataSchema); // Replace the POST route app.post('/api/data', async (req, res) => { const { name, email } = req.body; try { const newData = new DataModel({ name, email }); await newData.save(); res.status(201).json({ message: 'Data saved to DB successfully' }); } catch (error) { res.status(500).json({ message: 'Error saving data', error }); } });

Now, whenever a POST request is received, the backend saves the data to MongoDB.


Step 4: Running the Application

  1. Start Backend

bash
node backend/server.js
  1. Open Frontend

Open frontend/index.html in your browser (just double-click it or use Live Server if using VS Code).

  1. Submit Form

Fill in the name and email, hit “Send.” Check your terminal—you should see the POST data logged or saved to MongoDB.


Step 5: Testing with Postman (Optional)

Install Postman and make a POST request to:

bash
http://localhost:5000/api/data

Body (raw JSON):

json
{
"name": "Test User",
"email": "test@example.com"
}

You should get a success message back.


 Common Issues and Solutions

IssueSolution
CORS error in browserUse cors() middleware in Express
Server not receiving dataEnsure body-parser or express.json() is used
MongoDB connection errorMake sure MongoDB is running locally or use Atlas
Fetch API errors in frontendCheck for typos in the fetch URL or wrong port
Frontend not refreshing after POSTUse DOM manipulation to show response messages

Best Practices

  • Validate input on both frontend and backend.

  • Use .env for sensitive config like DB URIs.

  • Use try-catch blocks for error handling.

  • Create a separate route file for scalability.

  • Use Mongoose models to structure data better.


Conclusion

Congratulations! You’ve just learned how to connect a backend to a frontend using a POST request. You saw how to:

  • Create a basic frontend with an HTML form

  • Handle a POST request using JavaScript’s fetch()

  • Set up a backend with Express

  • Connect to a MongoDB database and save data

This foundational knowledge is essential for full-stack development. You can now build more complex apps like user authentication systems, CRUD applications, and more!