Experiment 9: ExpressJS – Database, RESTful APIs
Write a program to connect MongoDB database using Mangoose and perform CRUD operations.
run the following commands in command prompt in your project folder
npm install --save mongoose@6.0
npm install --save pug
npm install --save body-parser
npm install --save multer
server.js
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose'); // Import mongoose
var multer = require('multer');
var upload = multer();
var app = express();
// Connect to MongoDB (Replace <your_connection_string> with your actual MongoDB URI)
mongoose.connect('mongodb://127.0.0.1:27017/library1', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('MongoDB connection error:', err));
// Define Mongoose Schema
var personSchema = new mongoose.Schema({
name: String,
age: Number,
nationality: String
});
var Person = mongoose.model("Person", personSchema);
// Middleware for parsing request body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); // For form-urlencoded
app.use(upload.array()); // For multipart/form-data
app.use(express.static('public')); // Serve static files if needed
app.get('/', function(req, res) {
// Sending HTML directly
res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Tester</title>
</head>
<body>
<h2>Form Tester</h2>
<form action="/" method="POST">
<div>
<label for="name1">Name1:</label>
<input type="text" name="name" required>
</div>
<br>
<div>
<label for="age">Age:</label>
<input type="number" name="age" required>
</div>
<br>
<div>
<label for="nationality">Nationality:</label>
<input type="text" name="nationality" required>
</div>
<br>
<button type="submit">Add me</button>
</form>
</body>
</html>
`);
});
app.post('/', function(req, res) {
console.log(req.body); // Logs submitted form data
var personInfo = req.body; // Get the parsed information
if (!personInfo.name || !personInfo.age || !personInfo.nationality) {
return res.send(`
<h3 style="color:red">Sorry, you provided wrong info</h3>
`);
}
var newPerson = new Person({
name: personInfo.name,
age: personInfo.age,
nationality: personInfo.nationality
});
newPerson.save()
.then(() => {
res.send(`
<h3 style="color:green">New person added</h3>
<p>Name: ${personInfo.name}</p>
<p>Age: ${personInfo.age}</p>
<p>Nationality: ${personInfo.nationality}</p>
`);
})
.catch(err => {
console.error("Database error:", err);
res.send('<h3 style="color:red">Database error</h3>');
});
});
// Start server
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
In Visual studio code, open server.js, run->debug
open browser and test http://localhost:3000
fill the form and test data storing in mongodb (library1 database)
by opening mongodb compass tool
Write a program to develop a single page application using RESTful APIs
Conceptual background:
A single page application(SPA) loads only one HTML page and dynamically
updates content using Javascript and REST APIs without reloading the
entire page.
Example: Google MAPs, Facebook, E-MEdia etc
REST (Representational State Transfer) is an architectural style
where:
Data is accessed using HTTP methods
Communication happens using JSON
| HTTP Method | Operation |
|---|---|
| GET | Read data |
| POST | Create data |
| PUT | Update data |
| DELETE | Delete data |
Project structure:
spa-express/ │ ├── server.js ├── package.json └── public/ └── index.html
Backend: Express.js REST API (server.js)
const express = require("express");
const app = express();
const PORT = 3000;
app.use(express.json());
app.use(express.static("public"));
let users = [
{ id: 1, name: "Rakesh" },
{ id: 2, name: "Rohith" },
{ id: 3, name: "Veena" }
];
// GET API
app.get("/api/users", (req, res) => {
res.json(users);
});
// POST API
app.post("/api/users", (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name
};
users.push(newUser);
res.json(newUser);
});
// Start server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Frontend: Single Page Application (index.html)
<!DOCTYPE html>
<html>
<head>
<title>SPA using Express REST API</title>
</head>
<body>
<h2>User List</h2>
<ul id="userList"></ul>
<input type="text" id="username" placeholder="Enter name">
<button onclick="addUser()">Add User</button>
<script>
// Load users (GET)
fetch("/api/users")
.then(res => res.json())
.then(data => {
const list = document.getElementById("userList");
data.forEach(user => {
list.innerHTML += `<li>${user.name}</li>`;
});
});
// Add user (POST)
function addUser() {
const name = document.getElementById("username").value;
fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name })
})
.then(res => res.json())
.then(user => {
document.getElementById("userList").innerHTML += `<li>${user.name}</li>`;
});
}
</script>
</body>
</html>
working:Browser (SPA) | | fetch() request vExpress REST API | | JSON response vBrowser updates page (No reload)
Browser (SPA)
|
| fetch() request
v
Express REST API
|
| JSON response
v
Browser updates page (No reload)
Comments
Post a Comment