Develop An Express Web Application That Can Interact With REST API To Perform CRUD Operations On S
Develop An Express Web Application That Can Interact With REST API To Perform CRUD Operations On S
Solution :
Firstly we need to create a new folder and open the folder in the command
prompt and enter a command as below:
npm init -y
package.js
{
"name": "10",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"express": "^5.1.0",
"sqlite3": "^5.1.7"
}
}
db.js
const sqlite3 = require('sqlite3').verbose();
// Function to initialize the database schema
function initializeDatabase() {
const db = new sqlite3.Database('./mydatabase.db', (err) => {
if (err) {
console.error(err.message);
} else {
console.log('Connected to the SQLite database.');
createStudentsTable(db);
}
});
// Update a student
app.put('/students/:id', (req, res) => {
const id = req.params.id;
const{ name, age, grade } = req.body;
db.run('UPDATE students SET name = ?, age = ?, grade = ? WHERE id = ?',
[name, age, grade, id], function (err) {
if (err) {
return console.error(err.message);
}
res.json({ updatedID:id });
});
});
// Delete a student
app.delete('/students/:id', (req, res) => {
const id = req.params.id;
db.run('DELETE FROM students WHERE id = ?', id, function (err) {
if (err) {
return console.error(err.message);
}
res.json({ deletedID:id });
});
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
OUTPUT