0% found this document useful (0 votes)
2 views3 pages

Spp 5 aniket

The document outlines an experiment conducted by Aniket Dayanand Patil, focusing on implementing routes for serving static files and integrating a MongoDB database with a Node.js application for dynamic content generation. It includes HTML and JavaScript code for a ToDo application that allows users to add tasks and fetch existing ones from the database. The server setup using Express and Mongoose is also described, detailing the handling of API requests and responses.

Uploaded by

ap01720172
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

Spp 5 aniket

The document outlines an experiment conducted by Aniket Dayanand Patil, focusing on implementing routes for serving static files and integrating a MongoDB database with a Node.js application for dynamic content generation. It includes HTML and JavaScript code for a ToDo application that allows users to add tasks and fetch existing ones from the database. The server setup using Express and Mongoose is also described, detailing the handling of API requests and responses.

Uploaded by

ap01720172
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Experiment No 5

Name: Aniket Dayanand Patil


Roll No: 46
Aim: Implement routes to serve static files and a database (e.g., MongoDB) with the Node.js
handle dynamic content generation. Integrate server.

<!DOCTYPE html> todos.forEach(todo => {

<html lang="en"> const listItem =


document.createElement('li');
<head>
listItem.textContent = todo.task;
<meta charset="UTF-8">
todoList.appendChild(listItem);
<meta name="viewport"
});}
content="width=device-width, initial-
scale=1.0">

<title>ToDo App</title> form.addEventListener('submit', async


(event) => {
<link rel="stylesheet" href="css/style.css">
event.preventDefault();
</head>
const todoValue =
<body>
document.getElementById('todoInput').value;
<h1>ToDo List</h1>
try {const response = await
<form id="todoForm"> fetch('/api/todos', {

<input type="text" id="todoInput" method: 'POST',


placeholder="Enter a new task" required />
headers: {
<button type="submit">Add
'Content-Type':
Task</button>
'application/json',
</form>
} body: JSON.stringify({ task:
<ul id="todoList"></ul> todoValue }), });

<script> const data = await response.json();

const form = if (response.ok) {


document.getElementById('todoForm');
fetchTodos();
const todoList =
form.reset();
document.getElementById('todoList');
} else {
async function fetchTodos() {
alert('Error adding task');
const response = await
fetch('/api/todos'); }}catch (error) {

const todos = await response.json(); alert('Request failed: ' +


error.message); } });
todoList.innerHTML = '';
fetchTodos(); </script></body></html> .connect(mongoURI, {

body {font-family: Arial, sans-serif; useNewUrlParser: true,

padding: 20px; useUnifiedTopology: true,

}h1 {color: #333; }) .then(() => console.log("MongoDB


connected"))
}form {
.catch((err) => console.log("Database
margin-bottom: 20px;
connection error: ", err));
}input {
app.use(bodyParser.json());
padding: 10px;
app.use(bodyParser.urlencoded({ extended:
font-size: 16px;} true }));

button { padding: 10px; const __filename =


fileURLToPath(import.meta.url);
font-size: 16px;
const _dirname = path.dirname(_filename);
cursor: pointer;
app.use(express.static(path.join(__dirname,
}ul { "public")));
list-style: none; app.get("/", (req, res) => {
padding: 0; res.sendFile(path.join(__dirname, "public",
}li { padding: 10px; "index.html"));

background: #f9f9f9; });app.post("/api/todos", async (req, res) => {

margin-bottom: 5px; try {

border: 1px solid #ddd; const { task } = req.body;

}Server.js const newToDo = new ToDo({ task });

import express from "express"; const savedToDo = await newToDo.save();

import mongoose from "mongoose"; res.status(201).json(savedToDo);

import bodyParser from "body-parser"; } catch (error) {

import path from "path"; res.status(500).json({ message: "Error


adding task", error }); }});
import ToDo from "./models/Todo.js";
app.get("/api/todos", async (req, res) => {
import { fileURLToPath } from "url";
try {
const app = express();
const todos = await ToDo.find();
const port = 5000;
res.status(200).json(todos);
const mongoURI =
mongodb+srv://abc1577:veVloV8rUKaW9aLA } catch (error) {
@cluster0.6m7xsik.mongodb.net/spp_todo; res.status(500).json({ message: "Error
mongoose fetching todos", error }); }});
app.listen(port, () => {

console.log(Server running at
http://localhost:${port});});

Output:

You might also like