nodejs制作图书管理系统
时间: 2023-11-21 09:58:12 浏览: 111
基于JavaScript语言Web项目图书管理系统(源代码+md说明文档)-计算机专业精品前端课程设计
Node.js是一个基于Chrome V8引擎的JavaScript运行环境,可以用于开发服务器端应用程序。下面是使用Node.js制作图书管理系统的步骤:
1.安装Node.js和MySQL数据库,并创建一个名为bookstore的数据库。
2.使用npm安装Express框架和mysql模块,用于搭建服务器和连接数据库。
3.创建一个名为index.js的主入口文件,用于路由分配和启动服务器。
4.创建一个名为router.js的路由文件,用于处理不同的URL请求。
5.创建一个名为db.js的数据库连接文件,用于连接MySQL数据库。
6.创建一个名为book.js的业务逻辑文件,用于实现图书信息的增删改查功能。
7.创建一个名为book.html的前端页面文件,用于展示图书信息和与后端进行交互。
8.在index.js中引入路由文件、数据库连接文件和业务逻辑文件,并启动服务器。
9.在router.js中编写不同URL请求的处理函数,例如获取所有图书信息、添加图书信息、修改图书信息和删除图书信息等。
10.在db.js中编写连接MySQL数据库的代码,并导出连接对象。
11.在book.js中编写业务逻辑代码,例如查询所有图书信息、添加图书信息、修改图书信息和删除图书信息等。
12.在book.html中编写前端页面代码,例如展示所有图书信息、添加图书信息、修改图书信息和删除图书信息等。
下面是一个简单的示例代码:
```javascript
// index.js
const express = require('express');
const router = require('./router');
const db = require('./db');
const book = require('./book');
const app = express();
const port = 3000;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
router(app, book);
db.connect(() => {
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
});
// router.js
module.exports = (app, book) => {
app.get('/books', book.getAll);
app.post('/books', book.add);
app.put('/books/:id', book.update);
app.delete('/books/:id', book.remove);
};
// db.js
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'bookstore',
});
module.exports = {
connect: (callback) => {
connection.connect((err) => {
if (err) {
console.error(`Error connecting to database: ${err.stack}`);
return; }
console.log(`Connected to database as id ${connection.threadId}`);
callback();
});
},
query: (sql, params, callback) => {
connection.query(sql, params, (err, results, fields) => {
if (err) {
console.error(`Error executing query: ${err.stack}`);
return;
}
callback(results);
});
},
};
// book.js
const db = require('./db');
module.exports = {
getAll: (req, res) => {
db.query('SELECT * FROM books', [], (results) => {
res.json(results);
});
},
add: (req, res) => {
const { title, author, price } = req.body;
db.query('INSERT INTO books (title, author, price) VALUES (?, ?, ?)', [title, author, price], (results) => {
res.json({ message: 'Book added successfully' });
});
},
update: (req, res) => {
const { id } = req.params;
const { title, author, price } = req.body;
db.query('UPDATE books SET title = ?, author = ?, price = ? WHERE id = ?', [title, author, price, id], (results) => {
res.json({ message: 'Book updated successfully' });
});
},
remove: (req, res) => {
const { id } = req.params;
db.query('DELETE FROM books WHERE id = ?', [id], (results) => {
res.json({ message: 'Book deleted successfully' });
});
},
};
// book.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Bookstore</title>
</head>
<body>
<h1>Bookstore</h1>
<table>
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody id="book-list">
</tbody>
</table>
<form id="add-book-form">
<h2>Add Book</h2>
<div>
<label>Title:</label>
<input type="text" name="title">
</div>
<div>
<label>Author:</label>
<input type="text" name="author">
</div>
<div>
<label>Price:</label>
<input type="number" name="price">
</div>
<button type="submit">Add</button>
</form>
<script>
const bookList = document.getElementById('book-list');
const addBookForm = document.getElementById('add-book-form');
function renderBooks() {
fetch('/books')
.then(response => response.json())
.then(books => {
bookList.innerHTML = '';
books.forEach(book => {
const tr = document.createElement('tr');
const titleTd = document.createElement('td');
const authorTd = document.createElement('td');
const priceTd = document.createElement('td');
const actionTd = document.createElement('td');
const editButton = document.createElement('button');
const deleteButton = document.createElement('button');
titleTd.innerText = book.title;
authorTd.innerText = book.author;
priceTd.innerText = book.price;
editButton.innerText = 'Edit';
deleteButton.innerText = 'Delete';
editButton.addEventListener('click', () => {
const title = prompt('Enter new title:', book.title);
const author = prompt('Enter new author:', book.author);
const price = prompt('Enter new price:', book.price);
fetch(`/books/${book.id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ title, author, price })
})
.then(response => response.json())
.then(data => {
alert(data.message);
renderBooks();
});
});
deleteButton.addEventListener('click', () => {
if (confirm('Are you sure you want to delete this book?')) {
fetch(`/books/${book.id}`, {
method: 'DELETE'
})
.then(response => response.json())
.then(data => {
alert(data.message);
renderBooks();
});
}
});
actionTd.appendChild(editButton);
actionTd.appendChild(deleteButton);
tr.appendChild(titleTd);
tr.appendChild(authorTd);
tr.appendChild(priceTd);
tr.appendChild(actionTd);
bookList.appendChild(tr);
});
});
}
addBookForm.addEventListener('submit', (event) => {
event.preventDefault();
const title = addBookForm.elements.title.value;
const author = addBookForm.elements.author.value;
const price = addBookForm.elements.price.value;
fetch('/books', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ title, author, price })
})
.then(response => response.json())
.then(data => {
alert(data.message);
addBookForm.reset();
renderBooks();
});
});
renderBooks();
</script>
</body>
</html>
```
阅读全文