Objective: Learn to create an interactive web page with a form that populates its fields from JSON data pulled via AJAX from a Node.js server. After user input, the data is persisted back to the server.
Part 1: Setting Up the Backend (Node.js)
Step 1: Initialize a new Node.js project.
bashCopy code
npm init -y
Step 2: Install necessary packages.
bashCopy code
npm install express body-parser
Step 3: Create a server.js file:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// Middlewares
app.use(bodyParser.json());
// Initial data
let formData = {
name: "",
email: "",
};
// Routes
app.get('/getFormData', (req, res) => {
res.json(formData);
});
app.post('/updateFormData', (req, res) => {
formData = req.body;
res.json({ status: 'success' });
});
// Start server
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Part 2: Creating the Frontend (HTML, CSS, and JavaScript)