Explore / Programming <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport"… Save Share Download ▾ ReportJump to turn (7) 1 管理员页面 table { width: 100%; border-collapse: collapse; } th, td { border: 1px sol 2 2admin.html:373 Record ID: undefined控制台弹出 管理员页面 table { width: 100%; border-coll 3 admin.html:373 Record ID: undefined还是获取不到数据id 管理员页面 table { width: 100%; border- 4 管理员页面 table { width: 100%; border-collapse: collapse; } th, td { border: 1px sol 5 管理员页面 table { width: 100%; border-collapse: collapse; } th, td { border: 1px sol 6 管理员页面 table { width: 100%; border-collapse: collapse; } th, td { border: 1px sol 7 管理员页面 table { width: 100%; border-collapse: collapse; } th, td { border: 1px sol Copy first prompt
Other models, same or similar prompt Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 7 (14 messages)
Language en
Conversation date Dec 5, 2024
Added to archive Nov 17, 2026
ID 01m7h42ajhqt872zhf73xj2fr9Source & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: e2ddac7e272b17cedfb1a3eb7d7343b7
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
code Copy code
th,
td {
border: 1px solid #ddd;
padding: 8px;
}
th {
background-color: #f2f2f2;
text-align: left;
}
code Copy code
// 根据type动态创建表单
switch (type) {
case 'add':
formContainer.innerHTML = `
<input type="text" placeholder="书名">
<input type="text" placeholder="作者">
<input type="number" placeholder="出版年份">
<button onclick="addBook()">添加</button>
`;
break;
case 'delete':
formContainer.innerHTML = `
<h2>删除图书</h2>
<input type="text" id="bookTitle" placeholder="输入书名" style="width: 200px;" />
<button onclick="deleteBook()">删除</button>
`;
break;
case 'borrowRecords':
formContainer.innerHTML = `<h2>借阅记录</h2><div id="borrowRecordsList"></div>`;
loadBorrowRecords();
break;
case 'edit':
formContainer.innerHTML = `
<h2>修改图书</h2>
<input type="text" placeholder="旧书名" id="oldTitle">
<input type="text" placeholder="新书名" id="newTitle">
<input type="text" placeholder="新作者" id="newAuthor">
<input type="number" placeholder="新出版年份" id="newYearPublished">
<button onclick="editBook()">修改</button>
`;
break;
case 'search':
formContainer.innerHTML = `
<input type="text" placeholder="搜索关键词" id="searchKeyword">
<button onclick="searchBooks()">查询</button>
`;
break;
case 'userManagement':
loadUsers().then(users => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">用户管理</h2>
<div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
<ul style="list-style-type: none; padding: 0;">
`;
users.forEach(user => {
formContainer.innerHTML += `
<li style="margin: 10px 0;">
${user.username}
<button onclick="editUserForm('${user.id}')">编辑</button>
<button onclick="deleteUser('${user.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
});
break;
case 'dataManagement':
formContainer.innerHTML = `
<h2>数据管理</h2>
<!-- 这里可以添加数据管理的相关表单或内容 -->
`;
loadBooks(); // 正确的位置
break;
case 'borrowRecords':
formContainer.innerHTML = `
<h2>借阅记录</h2>
<!-- 这里可以添加借阅记录的相关表单或内容 -->
`;
break;
case 'editUser':
fetch(`http://localhost:3000/admin/get-user/${id}`)
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch user data');
}
return response.json();
})
.then(user => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<input type="hidden" value="${id}" name="id">
<input type="text" placeholder="用户名" value="${user.username}" name="username">
<input type="password" placeholder="密码" name="password">
<select name="role">
<option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
<option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
</select>
<button onclick="editUser(${id})">保存</button>
`;
})
.catch(error => {
console.error('Error fetching user data:', error);
alert('Failed to fetch user data: ' + error.message);
});
break;
case 'deleteUser':
if (confirm(`确定要删除用户ID为${id}的用户吗?此操作不可撤销!`)) {
deleteUser(id);
}
break;
default:
formContainer.style.display = 'none';
}
}
function addBook() {
// 获取表单数据
const formContainer = document.getElementById('formContainer');
const title = formContainer.querySelector('input[placeholder="书名"]').value;
const author = formContainer.querySelector('input[placeholder="作者"]').value;
const year_published = formContainer.querySelector('input[placeholder="出版年份"]').value; // 使用正确的变量名
// 发送增加图书的请求
fetch('http://localhost:3000/admin/add-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin' // 假设已经在某处设置了用户类型
},
body: JSON.stringify({ title, author, year_published }) // 使用正确的变量名
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Book added:', data);
alert('图书添加成功:' + data); // 显示成功消息
// 可选:清空表单
formContainer.innerHTML = '';
formContainer.style.display = 'none';
// 可选:更新图书列表(如果有的话)
})
.catch(error => {
console.error('Error adding book:', error);
alert('添加图书时出错:' + error.message);
});
}
function searchBooks() {
const searchKeyword = document.getElementById('searchKeyword').value;
fetch('http://localhost:3000/user/search-books', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ keyword: searchKeyword })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
displaySearchResults(data);
})
.catch(error => {
console.error('Error searching books:', error);
alert('搜索图书时出错:' + error.message);
});
}
function displaySearchResults(books) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<div>
<button onclick="showForm('search')">返回继续搜索</button>
</div>
<h2>搜索结果</h2>
`;
if (books.length === 0) {
formContainer.innerHTML += '<p>未找到图书。</p>';
} else {
const resultsList = document.createElement('ul');
books.forEach(book => {
const listItem = document.createElement('li');
listItem.textContent = `${book.title} by ${book.author} (${book.year_published})`;
resultsList.appendChild(listItem);
});
formContainer.appendChild(resultsList);
}
}
function loadBooks() {
console.log('Starting to load books...');
return fetch('http://localhost:3000/admin/get-books')
.then(response => {
console.log('Received response from get-books:', response);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(books => {
console.log('Loaded books data:', books);
displayBooks(books);
return Promise.resolve(); // 显式返回一个已解决的Promise,确保外层能正确链式调用
})
.catch(error => {
console.error('Error loading books:', error);
alert('加载图书时出错:' + error.message);
return Promise.reject(error); // 出现错误时返回一个被拒绝的Promise,传播错误
});
}
function displayBooks(books) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">图书管理</h2>
<div class="book-list-container">
<ul>
`;
books.forEach(book => {
formContainer.innerHTML += `
<li>
${book.title} by ${book.author} (${book.year_published})
<button onclick="editBookForm('${book.id}')">编辑</button>
<button onclick="deleteBookConfirm('${book.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
return Promise.resolve();
}
code Copy code
function loadUsers() {
return fetch('http://localhost:3000/admin/get-users')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(users => {
displayUsers(users);
return users; // 将处理后的用户数据返回,使得外层能接收到这个 Promise 结果
})
.catch(error => {
console.error('Error loading users:', error);
alert('加载用户时出错:' + error.message);
throw error; // 可以选择重新抛出错误,让调用处能进一步处理
});
}
function displayUsers(users) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">用户管理</h2>
<div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
<ul style="list-style-type: none; padding: 0;">
`;
users.forEach(user => {
formContainer.innerHTML += `
<li style="margin: 10px 0;">
${user.username}
<button onclick="editUserForm('${user.id}')">编辑</button>
<button onclick="deleteUserConfirm('${user.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
}
function loadBorrowRecords() {
fetch('http://localhost:3000/admin/borrow-records')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(records => {
displayBorrowRecords(records);
})
.catch(error => {
console.error('Error loading borrow records:', error);
alert('加载借阅记录时出错:' + error.message);
});
}
function displayBorrowRecords(records) {
const borrowRecordsList = document.getElementById('borrowRecordsList');
borrowRecordsList.innerHTML = ''; // 清空之前的内容
if (records.length === 0) {
borrowRecordsList.innerHTML = '<p>无借阅记录。</p>';
} else {
const table = document.createElement('table');
table.innerHTML = `
<tr>
<th>用户名</th>
<th>书名</th>
<th>作者</th>
<th>借阅日期</th>
<th>操作</th>
</tr>
`;
records.forEach(record => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${record.username}</td>
<td>${record.title}</td>
<td>${record.author}</td>
<td>${record.borrow_date}</td>
<td>
<button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
</td>
`;
table.appendChild(row);
});
borrowRecordsList.appendChild(table);
}
}
}
code Copy code
function deleteBookConfirm(bookId) {
if (!bookId) {
alert('无效的图书ID');
return;
}
if (confirm(`确定要删除图书ID为${bookId}的图书吗?此操作不可撤销!`)) {
deleteBook(bookId);
}
}
function deleteBook(bookId) {
if (!bookId) {
alert('无效的图书ID');
return;
}
code Copy code
fetch('http://localhost:3000/admin/delete-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ id: bookId }) // 使用书籍 ID
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Book deleted:', data);
alert('图书删除成功');
loadBooks(); // 重新加载图书列表
})
.catch(error => {
console.error('Error deleting book:', error);
alert('删除图书时出错:' + error.message);
});
}
function editBook() {
const newTitle = document.getElementById('newTitle').value.trim();
const newAuthor = document.getElementById('newAuthor').value.trim();
const newYearPublished = document.getElementById('newYearPublished').value.trim();
code Copy code
// 简单验证输入框是否为空
if (!newTitle || !newAuthor || !newYearPublished) {
alert('请填写所有修改信息');
return;
}
const oldTitle = document.getElementById('oldTitle').value; // 注意,没有trim(),因为oldTitle是禁用输入,不应更改
fetch('http://localhost:3000/admin/edit-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ oldTitle, newTitle, newAuthor, newYearPublished })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok: ' + response.statusText);
}
return response.text();
})
.then(data => {
console.log('Book edited:', data);
alert('图书修改成功');
showForm('dataManagement'); // 返回数据管理界面
})
.catch(error => {
console.error('Error editing book:', error);
alert('修改图书时出错:' + error.message);
});
}
function deleteBorrowRecordConfirm(recordId) {
console.log('Attempting to delete record with ID:', recordId);
if (!recordId) {
alert('无效的借阅记录ID');
return;
}
if (confirm(确定要删除借阅记录ID为${recordId}的记录吗?此操作不可撤销!)) {
deleteBorrowRecord(recordId);
}
}
function deleteBorrowRecord(recordId) {
fetch('http://localhost:3000/admin/delete-borrow-record ', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ id: recordId }) // 发送要删除记录的 ID
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Borrow record deleted:', data);
alert('借阅记录删除成功');
loadBorrowRecords(); // 重新加载借阅记录列表
})
.catch(error => {
console.error('Error deleting borrow record:', error);
alert('删除借阅记录时出错:' + error.message);
});
}
const app = express();
app.use(cors());
app.use(bodyParser.json());
// MySQL数据库连接配置
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456', // 替换为你的MySQL密码
database: 'librarysystem'
});
db.connect(err => {
if (err) {
throw err;
}
console.log('MySQL connected...');
});
// 登录路由
app.post('/login', (req, res) => {
const { username, password } = req.body;
const query = 'SELECT * FROM users WHERE username = ? AND password = ?';
db.query(query, [username, password], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
console.log("Login successful, sending response:", results[0]);
res.json(results[0]);
} else {
res.status(400).json({ error: 'Invalid login' });
}
});
});
// 注册路由
app.post('/register', (req, res) => {
const { username, password } = req.body;
// 检查用户名是否已存在
const checkUserQuery = 'SELECT * FROM users WHERE username = ?';
db.query(checkUserQuery, [username], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
// 用户名已存在
res.status(400).json({ error: 'Username already exists' });
} else {
// 用户名不存在,可以注册
const insertUserQuery = 'INSERT INTO users (username, password, role) VALUES (?, ?, ?)';
db.query(insertUserQuery, [username, password, 'user'], (err, results) => {
if (err) {
res.status(500).json({ error: 'Failed to register user' });
} else {
res.status(201).send('User registered successfully');
}
});
}
});
});
// 管理员操作路由
// 添加图书
app.post('/admin/add-book', (req, res) => {
const { title, author, year_published } = req.body;
const query = 'INSERT INTO books (title, author, year_published) VALUES (?, ?, ?)';
db.query(query, [title, author, year_published], (err, results) => {
if (err) {
console.error('Error adding book:', err);
res.status(500).json({ error: 'Failed to add book' });
} else {
res.status(200).send('Book added successfully');
}
});
});
// 删除图书
app.post('/admin/delete-book', (req, res) => {
const { id } = req.body;
code Copy code
// 确保 ID 是有效的数字
if (!id || isNaN(id)) {
res.status(400).json({ error: 'Invalid book ID format' });
return;
}
const query = 'DELETE FROM books WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error deleting book:', err);
res.status(500).json({ error: 'Failed to delete book. Error details: ' + err.message });
} else {
// 检查是否有行被删除
if (results.affectedRows > 0) {
res.send('Book deleted');
} else {
res.status(404).send('No book found with this ID');
}
}
});
});
// 用户操作路由
// 搜索书籍
app.post('/user/search-books', (req, res) => {
const { keyword } = req.body;
const query = SELECT * FROM books WHERE id = ? OR title LIKE ? OR author LIKE ? ;
db.query(query, [keyword, %${keyword}%, %${keyword}%], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 添加收藏
// 获取用户的收藏书籍
app.get('/user/favorites/:userId', (req, res) => {
const { userId } = req.params;
const query = SELECT b.id, b.title, b.author FROM favorites f JOIN books b ON f.book_id = b.id WHERE f.user_id = ? ;
db.query(query, [userId], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 编辑图书
app.post('/admin/edit-book', (req, res) => {
const { oldTitle, newTitle, newAuthor, newYearPublished } = req.body;
code Copy code
// 验证每个字段
if (!oldTitle || !newTitle || !newAuthor || !newYearPublished) {
return res.status(400).json({ error: '所有字段都需要填写' });
}
const query = 'UPDATE books SET title=?, author=?, year_published=? WHERE title=?';
db.query(query, [newTitle, newAuthor, newYearPublished, oldTitle], (err, results) => {
if (err) {
console.error('Error editing book:', err);
return res.status(500).json({ error: 'Failed to edit book. Error details: ' + err.message });
}
// 检查是否有行被更新
if (results.affectedRows > 0) {
res.status(200).send('Book edited successfully');
} else {
res.status(404).send('No book found with that title for editing');
}
});
});
app.post('/admin/edit-book', (req, res) => {
const { oldTitle, newTitle, newAuthor, newYearPublished } = req.body;
code Copy code
// 验证每个字段
if (!oldTitle || !newTitle || !newAuthor || !newYearPublished) {
return res.status(400).json({ error: '所有字段都需要填写' });
}
const query = 'UPDATE books SET title=?, author=?, year_published=? WHERE title=?';
db.query(query, [newTitle, newAuthor, newYearPublished, oldTitle], (err, results) => {
if (err) {
console.error('Error editing book:', err);
return res.status(500).json({ error: 'Failed to edit book. Error details: ' + err.message });
}
// 检查是否有行被更新
if (results.affectedRows > 0) {
res.status(200).send('Book edited successfully');
} else {
res.status(404).send('No book found with that title for editing');
}
});
});
app.get('/admin/get-books', (req, res) => {
const query = 'SELECT * FROM books';
db.query(query, (err, results) => {
if (err) {
console.error('Error getting books:', err);
res.status(500).json({ error: 'Failed to get books' });
} else {
res.json(results);
}
});
});
// 获取所有用户
app.get('/admin/get-users', (req, res) => {
const query = 'SELECT * FROM users';
db.query(query, (err, results) => {
if (err) {
console.error('Error getting users:', err);
res.status(500).json({ error: 'Failed to get users' });
} else {
res.json(results);
}
});
});
// 借阅书籍
app.post('/user/borrow-book', (req, res) => {
const { userId, bookId } = req.body;
const query = 'INSERT INTO borrow_records (user_id, book_id, borrow_date) VALUES (?, ?, NOW())';
db.query(query, [userId, bookId], (err, results) => {
if (err) {
console.error('Error borrowing book:', err);
res.status(500).json({ error: 'Failed to borrow book' });
} else {
res.status(200).send('Book borrowed successfully');
}
});
});
// 获取借阅历史
app.get('/user/borrow-history/:userId', (req, res) => {
const { userId } = req.params;
const query = SELECT b.title, b.author, br.borrow_date FROM borrow_records br JOIN books b ON br.book_id = b.id WHERE br.user_id = ? ORDER BY br.borrow_date DESC ;
db.query(query, [userId], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 获取所有借阅记录(管理员用)
app.get('/admin/borrow-records', (req, res) => {
const query = SELECT u.username, b.title, b.author, br.borrow_date FROM borrow_records br JOIN users u ON br.user_id = u.id JOIN books b ON br.book_id = b.id ORDER BY br.borrow_date DESC ;
db.query(query, (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 编辑用户
app.post('/admin/edit-user', (req, res) => {
const { id, username, password, role } = req.body;
const query = 'UPDATE users SET username =?, password =?, role =? WHERE id =?';
db.query(query, [username, password, role, id], (err, results) => {
if (err) {
console.error('编辑用户信息出错,编辑的用户ID:', id);
console.error('错误信息:', err.message);
console.error('错误堆栈:', err.stack);
res.status(500).json({ error: 'Failed to edit user' });
} else {
console.log('用户信息编辑成功,编辑的用户ID:', id);
res.status(200).send('User edited successfully');
}
});
});
// 删除用户
app.post('/admin/delete-user', (req, res) => {
const { id } = req.body;
db.beginTransaction((err => {
if (err) {
console.error('Error starting transaction:', err);
res.status(500).send('Server error starting transaction');
return;
}
// 先删除 borrow_records 表中与该用户相关的记录
const deleteBorrowRecordsQuery = 'DELETE FROM borrow_records WHERE user_id =?';
db.query(deleteBorrowRecordsQuery, [id], (err => {
if (err) {
db.rollback(() => {
console.error('Error deleting related borrow records, rolling back transaction:', err);
res.status(500).send('Server error when deleting related borrow records, transaction rolled back');
});
return;
}
// 再删除 favorites 表中与该用户相关的记录
const deleteFavoritesQuery = 'DELETE FROM favorites WHERE user_id =?';
db.query(deleteFavoritesQuery, [id], (err => {
if (err) {
db.rollback(() => {
console.error('Error deleting related favorites, rolling back transaction:', err);
res.status(500).send('Server error when deleting related favorites, transaction rolled back');
});
return;
}
// 最后执行删除用户操作
const query = 'DELETE FROM users WHERE id =?';
db.query(query, [id], (err, results) => {
if (err) {
db.rollback(() => {
console.error('删除用户出错,要删除的用户ID:', id);
console.error('错误信息:', err.message);
console.error('错误堆栈:', err.stack);
res.status(500).send('Server error, transaction rolled back');
});
} else {
db.commit((err => {
if (err) {
console.error('Error committing transaction:', err);
res.status(500).send('Server error committing transaction');
return;
}
console.log('用户删除成功,删除的用户ID:', id);
res.send('User deleted');
}));
}
});
}));
}));
}));
});
//获取单个用户
app.get('/admin/get-user/:id', (req, res) => {
const { id } = req.params;
const query = 'SELECT * FROM users WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error getting user:', err);
res.status(500).json({ error: 'Failed to get user' });
} else if (results.length === 0) {
res.status(404).json({ error: 'User not found' });
} else {
res.json(results[0]);
}
});
});
// 编辑借阅记录(注意:通常借阅记录不需要编辑,但这里为了完整性提供示例)
app.post('/admin/edit-borrow-record', (req, res) => {
const { id, user_id, book_id, borrow_date } = req.body;
const query = 'UPDATE borrow_records SET user_id = ?, book_id = ?, borrow_date = ? WHERE id = ?';
db.query(query, [user_id, book_id, borrow_date, id], (err, results) => {
if (err) {
console.error('Error editing borrow record:', err);
res.status(500).json({ error: 'Failed to edit borrow record' });
} else {
res.status(200).send('Borrow record edited successfully');
}
});
});
// 删除借阅记录
app.post('/admin/delete-borrow-record', (req, res) => {
const { id } = req.body;
code Copy code
if (!id || isNaN(id)) {
return res.status(400).send('无效的借阅记录ID格式');
}
const query = 'DELETE FROM borrow_records WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error deleting borrow record:', err);
return res.status(500).send('服务器错误');
}
if (results.affectedRows > 0) {
res.send('借阅记录删除成功');
} else {
res.status(404).send('没有找到该借阅记录');
}
});
});
// 获取单个借阅记录详情的路由
app.get('/admin/get-borrow-record/:id', (req, res) => {
const { id } = req.params;
// 验证id是否为有效的数字且大于0
if (!Number.isInteger(Number(id)) || Number(id) <= 0) {
res.status(400).json({ error: 'Invalid borrow record ID format or value' });
return;
}
const query = SELECT * FROM borrow_records WHERE id =? ;
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error getting borrow record:', err);
res.status(500).json({ error: 'Failed to get borrow record. Error details: ' + err.message });
} else if (results.length === 0) {
res.status(404).json({ error: 'Borrow record not found' });
} else {
res.json(results[0]);
}
});
});
// 添加收藏路由
app.post('/user/add-favorite', (req, res) => {
const { userId, bookId } = req.body;
// 先检查该用户是否已经收藏了这本书
const checkFavoriteQuery = 'SELECT * FROM favorites WHERE user_id =? AND book_id =?';
db.query(checkFavoriteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
// 已收藏,提示用户
res.status(400).json({ error: 'This book has already been added to favorites' });
} else {
// 可以添加收藏,插入记录到 favorites 表
const insertFavoriteQuery = 'INSERT INTO favorites (user_id, book_id) VALUES (?,?)';
db.query(insertFavoriteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Failed to add to favorites' });
} else {
// 返回成功的 JSON 响应
res.status(200).json({ message: 'Book added to favorites successfully' });
}
});
}
});
});
// 删除收藏书籍路由
app.post('/user/delete-favorite', (req, res) => {
const { userId, bookId } = req.body;
const deleteQuery = 'DELETE FROM favorites WHERE user_id =? AND book_id =?';
db.query(deleteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error when deleting favorite' });
} else if (results.affectedRows === 0) {
// 如果受影响的行数为0,表示没有找到对应的收藏记录,即可能已经不存在该收藏了
res.status(400).json({ error: 'This book is not in your favorites' });
} else {
res.status(200).json({ message: 'Book removed from favorites successfully' });
}
});
});
// 从收藏中借阅书籍
app.post('/user/borrow-from-favorite', (req, res) => {
const { userId, bookId } = req.body;
// 先从收藏中删除这本书
const deleteFavoriteQuery = 'DELETE FROM favorites WHERE user_id = ? AND book_id = ?';
db.query(deleteFavoriteQuery, [userId, bookId], (err, deleteResults) => {
if (err) {
console.error('Error deleting favorite before borrowing:', err);
res.status(500).json({ error: 'Failed to borrow book from favorites' });
return;
}
if (deleteResults.affectedRows === 0) {
res.status(400).json({ error: 'This book is not in your favorites' });
return;
}
code Copy code
// 然后借阅这本书
const borrowQuery = 'INSERT INTO borrow_records (user_id, book_id, borrow_date) VALUES (?, ?, NOW())';
db.query(borrowQuery, [userId, bookId], (err, borrowResults) => {
if (err) {
console.error('Error borrowing book:', err);
res.status(500).json({ error: 'Failed to borrow book' });
} else {
// 返回成功的 JSON 响应
res.status(200).json({ message: 'Book borrowed from favorites successfully' });
}
});
});
});
// 监听端口
const PORT = 3000;
app.listen(PORT, () => {
console.log(Server running on port ${PORT});
});点击借阅记录删除时,工作台返回Attempting to delete record with ID: undefined,并弹出无效的借阅记录ID
Show full message · 1,099 lines Assistant2024-12-05 13:51 UTC Copy response
出现“Attempting to delete record with ID: undefined”以及弹出“无效的借阅记录ID”的错误提示,通常是因为在调用 deleteBorrowRecordConfirm 函数时未传递正确的参数(借阅记录的 ID)。我们可以从你给出的代码中检查一下相关的部分,确保在调用该函数时能够将有效的记录 ID 传入。
1. 检查 deleteBorrowRecordConfirm 函数的调用
确保在调用 deleteBorrowRecordConfirm 函数时,传递的 recordId 是从某个有效的数据源(如借阅记录表)中获取的。代码片段如下:
javascript Copy code
function displayBorrowRecords(records) {
const borrowRecordsList = document.getElementById('borrowRecordsList');
borrowRecordsList.innerHTML = ''; // 清空之前的内容
if (records.length === 0) {
borrowRecordsList.innerHTML = '<p>无借阅记录。</p>';
} else {
const table = document.createElement('table');
table.innerHTML = `
<tr>
<th>用户名</th>
<th>书名</th>
<th>作者</th>
<th>借阅日期</th>
<th>操作</th>
</tr>
`;
records.forEach(record => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${record.username}</td>
<td>${record.title}</td>
<td>${record.author}</td>
<td>${record.borrow_date}</td>
<td>
<button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
</td>
`;
table.appendChild(row);
});
borrowRecordsList.appendChild(table);
}
}
2. 记录 ID 的有效性
确保 record.id 是有效的,且在你调用 displayBorrowRecords(records) 函数时,传入的 records 数组中的每个对象都包含 id 属性。可以在 loadBorrowRecords 和 displayBorrowRecords 函数中添加调试日志:
2admin.html:373 Record ID: undefined控制台弹出
code Copy code
th,
td {
border: 1px solid #ddd;
padding: 8px;
}
th {
background-color: #f2f2f2;
text-align: left;
}
Show full message · 1,101 lines Assistant2024-12-05 13:53 UTC Copy response
要解决“Record ID: undefined”这一问题,我们需要确保在 loadBorrowRecords 和 displayBorrowRecords 函数中,借阅记录确实拥有有效的 id 属性。首先,我们需要修改后端 API 确保返回的借阅记录中确实包含 id 字段,并确保前端代码正确读取和传递 id。
1. 确保后端正确返回借阅记录 ID
在你的后端代码中,查询借阅记录的 API 已经正确选择了 ID 字段。确保在 getBorrowRecords API 中返回的对象符合预期,如下:
javascript Copy code
// 获取所有借阅记录(管理员用)
app.get('/admin/borrow-records', (req, res) => {
const query = `
SELECT br.id, u.username, b.title, b.author, br.borrow_date
FROM borrow_records br
JOIN users u ON br.user_id = u.id
JOIN books b ON br.book_id = b.id
ORDER BY br.borrow_date DESC
`;
db.query(query, (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
// Ensure that the ID is included in results
res.json(results);
}
});
});
确保在这里选择了 br.id,这样这个ID就可以在返回的数据中找到。
2. 修改前端代码
在前端 JavaScript 中,在 displayBorrowRecords 方法内,对每个借阅记录的 ID 进行调试(console.log),确保 record.id 的值正常获取:
admin.html:373 Record ID: undefined还是获取不到数据id
code Copy code
th,
td {
border: 1px solid #ddd;
padding: 8px;
}
th {
background-color: #f2f2f2;
text-align: left;
}
Show full message · 1,179 lines Assistant2024-12-05 13:56 UTC Copy response
如果在获取借阅记录的 id 时收到“Record ID: undefined”的情况,可能是由于查询的结果中没有返回 id 字段导致的,我们可以通过调试来找出问题所在。根据你提供的代码,可能的问题和解决方案如下:
1. 确保数据库返回 id
首先,检查你的数据库和查询,确保 borrow_records 表中的每条记录都具有 id 字段。如果你执行以下 SQL 语句:
sql Copy code
SELECT br.id, u.username, b.title, b.author, br.borrow_date
FROM borrow_records br
JOIN users u ON br.user_id = u.id
JOIN books b ON br.book_id = b.id
ORDER BY br.borrow_date DESC;
确保所有相关的借阅记录都能返回,包括 id。你可以在 MySQL 中直接运行这条查询语句并检查返回结果。
2. 检查前端代码
确保你在前端代码的 loadBorrowRecords 函数中,调用 API 地址是正确的:
javascript Copy code
function loadBorrowRecords() {
fetch('http://localhost:3000/admin/borrow-records') // 确保此 API 地址是正确的
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(records => {
console.log('Loaded borrow records:', records); // 检查返回的 records
displayBorrowRecords(records);
})
.catch(error => {
console.error('Error loading borrow records:', error);
alert('加载借阅记录时出错:' + error.message);
});
}
3. 调试返回的借阅记录
在 displayBorrowRecords 函数中,增加调试信息来查看返回的记录:
code Copy code
th,
td {
border: 1px solid #ddd;
padding: 8px;
}
th {
background-color: #f2f2f2;
text-align: left;
}
Show full message · 1,104 lines Assistant2024-12-05 14:02 UTC Copy response
要将删除图书的操作从使用图书 ID 改为使用图书标题进行删除,我们需要修改前端和后端代码。下面的步骤和代码更改将实现这个功能。
1. 修改前端代码
在前端代码中,我们需要更新 deleteBook() 函数以使其根据书名进行删除,替换掉之前传递 ID 的方式。代码示例:
javascript Copy code
function deleteBook() {
// 获取书名
const formContainer = document.getElementById('formContainer');
const bookTitle = formContainer.querySelector('#bookTitle').value; // 假设我们的输入框 ID 为 bookTitle
if (!bookTitle) {
alert('请输入书名以进行删除');
return;
}
fetch('http://localhost:3000/admin/delete-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ title: bookTitle }) // 发送书名
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Book deleted:', data);
alert('图书删除成功');
loadBooks(); // 重新加载图书列表
})
.catch(error => {
console.error('Error deleting book:', error);
alert('删除图书时出错:' + error.message);
});
}
function showForm(type) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = ''; // 清空之前的内容
formContainer.style.display = 'block';
switch (type) {
case 'delete':
formContainer.innerHTML = `
<h2>删除图书</h2>
<input type="text" id="bookTitle" placeholder="输入书名" style="width: 200px;" />
<button onclick="deleteBook()">删除</button>
`;
break;
// 处理其他类型的表单...
}
}
code Copy code
th,
td {
border: 1px solid #ddd;
padding: 8px;
}
th {
background-color: #f2f2f2;
text-align: left;
}
Show full message · 1,108 lines Assistant2024-12-05 14:06 UTC Copy response
要将删除图书的操作从使用图书 ID 改为使用书名,我们将分步骤进行代码修改,确保原有的图书管理模块和删除图书模块能够正确区分开,并通过书名完成删除。
1. 前端代码修改
在前端 HTML 部分,我们需要更新删除图书的表单,以便用户通过书名删除图书,并且与原有的基于 ID 的删除功能区别开。
修改 showForm 函数中的 delete 模块
在 showForm 函数中,添加一个输入框用于输入书名,并在按下删除按钮后进行删除操作。
javascript Copy code
function showForm(type, id = null) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = ''; // 清空之前的内容
formContainer.style.display = 'block';
// 根据type动态创建表单
switch (type) {
//... (existing cases)
case 'deleteByTitle':
formContainer.innerHTML = `
<h2>删除图书</h2>
<input type="text" id="bookTitle" placeholder="输入书名" style="width: 200px;" />
<button onclick="deleteBookByTitle()">删除</button>
`;
break;
//... (other cases)
}
}
添加 deleteBookByTitle 函数
javascript Copy code
function deleteBookByTitle() {
const bookTitle = document.getElementById('bookTitle').value; // 获取书名
if (!bookTitle) {
alert('请输入书名以进行删除');
return;
}
fetch('http://localhost:3000/admin/delete-book-by-title', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ title: bookTitle }) // 传递书名
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Book deleted:', data);
alert('图书删除成功');
loadBooks(); // 重新加载图书列表
})
.catch(error => {
console.error('Error deleting book:', error);
alert('删除图书时出错:' + error.message);
});
}
code Copy code
th,
td {
border: 1px solid #ddd;
padding: 8px;
}
th {
background-color: #f2f2f2;
text-align: left;
}
Show full message · 1,168 lines Assistant2024-12-05 14:15 UTC Copy response
要将删除图书的模块修改为根据书名删除图书,我们需要做以下几个步骤:修改前端代码以获取书名而不是 ID,并更新后端路由以处理通过书名删除书籍的请求。
1. 修改前端代码
在前端,我们需要创建一个新的表单来输入书名并进行删除。我们将使用 showForm 函数来显示删除书籍的用户界面。
更新 showForm 函数添加删除书籍的表单
javascript Copy code
function showForm(type, id = null) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = ''; // 清空之前的内容
formContainer.style.display = 'block';
// 根据 type 动态创建表单
switch (type) {
//... (已有的 case)
case 'delete':
formContainer.innerHTML = `
<h2>删除图书</h2>
<input type="text" id="bookTitle" placeholder="输入书名" style="width: 200px;" />
<button onclick="deleteBookByTitle()">删除</button>
`;
break;
//... (其他 case)
}
}
2. 添加删除书籍的函数
添加一个新的函数 deleteBookByTitle,这个函数将根据书名发送删除请求。
javascript Copy code
function deleteBookByTitle() {
const bookTitle = document.getElementById('bookTitle').value; // 获取书名
if (!bookTitle) {
alert('请输入书名以进行删除');
return;
}
fetch('http://localhost:3000/admin/delete-book-by-title', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ title: bookTitle }) // 发送书名
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Book deleted:', data);
alert('图书删除成功');
loadBooks(); // 重新加载图书列表
})
.catch(error => {
console.error('Error deleting book:', error);
alert('删除图书时出错:' + error.message);
});
}
code Copy code
th,
td {
border: 1px solid #ddd;
padding: 8px;
}
th {
background-color: #f2f2f2;
text-align: left;
}
Show full message · 1,168 lines Assistant2024-12-05 14:17 UTC Copy response
根据你的要求,我们将修改删除图书模块,使其通过书名而不是 ID 来删除图书。下面是所需的前端和后端代码的详细修改步骤。
1. 修改前端代码
在前端代码中,将删除图书的模块改为根据书名删除。我们会添加一个新的删除形式,该形式包含一个输入框用于输入书名。
修改 showForm 函数以包含删除书名的功能
javascript Copy code
function showForm(type, id = null) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = ''; // 清空之前的内容
formContainer.style.display = 'block';
// 根据type动态创建表单
switch (type) {
// ... 其他 case
case 'delete':
formContainer.innerHTML = `
<h2>删除图书</h2>
<input type="text" id="bookTitle" placeholder="输入书名" style="width: 200px;" />
<button onclick="deleteBookByTitle()">删除</button>
`;
break;
// ... 其他 case
}
}
新增删除图书的函数
javascript Copy code
function deleteBookByTitle() {
const bookTitle = document.getElementById('bookTitle').value; // 获取书名
if (!bookTitle) {
alert('请输入书名以进行删除');
return;
}
fetch('http://localhost:3000/admin/delete-book-by-title', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ title: bookTitle }) // 传递书名
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Book deleted:', data);
alert('图书删除成功');
loadBooks(); // 重新加载图书列表
})
.catch(error => {
console.error('Error deleting book:', error);
alert('删除图书时出错:' + error.message);
});
}
Copy first response
Not yet included in a published release.
function deleteUser(id) {
fetch(`http://localhost:3000/admin/delete-user`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok: ' + response.statusText);
}
return response.text();
})
.then(data => {
alert(data);
loadUsers(); // 刷新用户列表
})
.catch(error => {
console.error('Error deleting user:', error);
alert('删除用户时出现错误:' + error.message);
});
}
function editUserForm(id) {
fetch(`http://localhost:3000/admin/get-user/${id}`)
.then(response => {
if (!response.ok) {
throw new Error('获取用户信息失败,状态码:' + response.status);
}
return response.json();
})
.then(user => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<form id="editUserForm">
<input type="hidden" value="${id}" name="id">
<input type="text" placeholder="用户名" value="${user.username}" name="username">
<input type="password" placeholder="密码" name="password">
<select name="role">
<option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
<option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
</select>
<button type="button" onclick="editUser(${id})">保存</button>
</form>
`;
})
.catch(error => {
console.error('编辑用户信息获取出错:', error);
alert('获取用户信息失败,请稍后重试:' + error.message);
});
}
function editUser(id) {
const form = document.querySelector(`#editUserForm`);
if (!form || !(form instanceof HTMLFormElement)) {
console.error('Invalid form element');
return;
}
const formData = new FormData(form);
const data = Object.fromEntries(formData.entries());
// Simple validation for required fields
if (!data.username || !data.password || !data.role) {
alert('请填写所有必填字段');
return;
}
fetch(`http://localhost:3000/admin/edit-user`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
.then(response => response.text())
.then(data => {
alert(data);
loadUsers(); // 刷新用户列表
})
.catch(error => {
console.error('Error editing user:', error);
alert('编辑用户信息时出现错误,请稍后重试:' + error.message);
});
}
function editBookForm(bookId) {
// 先调用获取所有图书的后端路由以获取图书数据
fetch('http://localhost:3000/admin/get-books')
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch all books data');
}
return response.json();
})
.then(allBooks => {
// 在获取到的所有图书数据中查找对应id的图书
const targetBook = allBooks.find(book => book.id === Number(bookId));
if (!targetBook) {
alert('未找到对应图书信息,请确认图书ID是否正确');
return;
}
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2>修改图书</h2>
<input type="text" placeholder="旧书名" id="oldTitle" value="${targetBook.title}" disabled>
<input type="text" placeholder="新书名" id="newTitle">
<input type="text" placeholder="新作者" id="newAuthor">
<input type="number" placeholder="新出版年份" id="newYearPublished">
<button onclick="editBook()">保存</button>
`;
})
.catch(error => {
console.error('Error fetching book data:', error);
alert('获取图书信息失败,请稍后重试:' + error.message);
});
function displayBorrowRecords(records) {
console.log('Borrow records:', records); // Debug log
const borrowRecordsList = document.getElementById('borrowRecordsList');
borrowRecordsList.innerHTML = ''; // 清空之前的内容
if (records.length === 0) {
borrowRecordsList.innerHTML = '<p>无借阅记录。</p>';
} else {
const table = document.createElement('table');
table.innerHTML = `
<tr>
<th>用户名</th>
<th>书名</th>
<th>作者</th>
<th>借阅日期</th>
<th>操作</th>
</tr>
`;
records.forEach(record => {
console.log('Record ID:', record.id); // Debug log
const row = document.createElement('tr');
row.innerHTML = `
<td>${record.username}</td>
<td>${record.title}</td>
<td>${record.author}</td>
<td>${record.borrow_date}</td>
<td>
<button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
</td>
`;
table.appendChild(row);
});
borrowRecordsList.appendChild(table);
}
}
3. 调试步骤
确保数据完整性 :查看控制台输出,确保每个记录都有有效的 id。这可以帮助你确认数据是否在发送请求之前就已经丢失。
确认 API 响应 :在浏览器的开发者工具中查看从 /admin/borrow-records 获取的 API 响应,确保这些记录在 JSON 中确实包含 id 字段。
查看关键路径 :确保没有代码逻辑在 loadBorrowRecords 与 displayBorrowRecords 之间对 records 数组进行了不必要的更改或转换。
4. 解决问题 完成以上检查后,你应该能够识别出问题的根源。如果 id 属于定义不全或未定义状态,请根据 API 的响应格式进行相应的调整,确保每个借阅记录都含有 id。
经过修复后,你应能在删除借阅记录时,顺利的传递有效的 ID。如果问题依旧,建议分享更多的代码或调试信息,以便更精确地进行分析。
// 根据type动态创建表单
switch (type) {
case 'add':
formContainer.innerHTML = `
<input type="text" placeholder="书名">
<input type="text" placeholder="作者">
<input type="number" placeholder="出版年份">
<button onclick="addBook()">添加</button>
`;
break;
case 'delete':
formContainer.innerHTML = `
<h2>删除图书</h2>
<input type="text" id="bookTitle" placeholder="输入书名" style="width: 200px;" />
<button onclick="deleteBook()">删除</button>
`;
break;
case 'borrowRecords':
formContainer.innerHTML = `<h2>借阅记录</h2><div id="borrowRecordsList"></div>`;
loadBorrowRecords();
break;
case 'edit':
formContainer.innerHTML = `
<h2>修改图书</h2>
<input type="text" placeholder="旧书名" id="oldTitle">
<input type="text" placeholder="新书名" id="newTitle">
<input type="text" placeholder="新作者" id="newAuthor">
<input type="number" placeholder="新出版年份" id="newYearPublished">
<button onclick="editBook()">修改</button>
`;
break;
case 'search':
formContainer.innerHTML = `
<input type="text" placeholder="搜索关键词" id="searchKeyword">
<button onclick="searchBooks()">查询</button>
`;
break;
case 'userManagement':
loadUsers().then(users => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">用户管理</h2>
<div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
<ul style="list-style-type: none; padding: 0;">
`;
users.forEach(user => {
formContainer.innerHTML += `
<li style="margin: 10px 0;">
${user.username}
<button onclick="editUserForm('${user.id}')">编辑</button>
<button onclick="deleteUser('${user.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
});
break;
case 'dataManagement':
formContainer.innerHTML = `
<h2>数据管理</h2>
<!-- 这里可以添加数据管理的相关表单或内容 -->
`;
loadBooks(); // 正确的位置
break;
case 'borrowRecords':
formContainer.innerHTML = `
<h2>借阅记录</h2>
<!-- 这里可以添加借阅记录的相关表单或内容 -->
`;
break;
case 'editUser':
fetch(`http://localhost:3000/admin/get-user/${id}`)
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch user data');
}
return response.json();
})
.then(user => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<input type="hidden" value="${id}" name="id">
<input type="text" placeholder="用户名" value="${user.username}" name="username">
<input type="password" placeholder="密码" name="password">
<select name="role">
<option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
<option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
</select>
<button onclick="editUser(${id})">保存</button>
`;
})
.catch(error => {
console.error('Error fetching user data:', error);
alert('Failed to fetch user data: ' + error.message);
});
break;
case 'deleteUser':
if (confirm(`确定要删除用户ID为${id}的用户吗?此操作不可撤销!`)) {
deleteUser(id);
}
break;
default:
formContainer.style.display = 'none';
}
}
function addBook() {
// 获取表单数据
const formContainer = document.getElementById('formContainer');
const title = formContainer.querySelector('input[placeholder="书名"]').value;
const author = formContainer.querySelector('input[placeholder="作者"]').value;
const year_published = formContainer.querySelector('input[placeholder="出版年份"]').value; // 使用正确的变量名
// 发送增加图书的请求
fetch('http://localhost:3000/admin/add-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin' // 假设已经在某处设置了用户类型
},
body: JSON.stringify({ title, author, year_published }) // 使用正确的变量名
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Book added:', data);
alert('图书添加成功:' + data); // 显示成功消息
// 可选:清空表单
formContainer.innerHTML = '';
formContainer.style.display = 'none';
// 可选:更新图书列表(如果有的话)
})
.catch(error => {
console.error('Error adding book:', error);
alert('添加图书时出错:' + error.message);
});
}
function searchBooks() {
const searchKeyword = document.getElementById('searchKeyword').value;
fetch('http://localhost:3000/user/search-books', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ keyword: searchKeyword })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
displaySearchResults(data);
})
.catch(error => {
console.error('Error searching books:', error);
alert('搜索图书时出错:' + error.message);
});
}
function displaySearchResults(books) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<div>
<button onclick="showForm('search')">返回继续搜索</button>
</div>
<h2>搜索结果</h2>
`;
if (books.length === 0) {
formContainer.innerHTML += '<p>未找到图书。</p>';
} else {
const resultsList = document.createElement('ul');
books.forEach(book => {
const listItem = document.createElement('li');
listItem.textContent = `${book.title} by ${book.author} (${book.year_published})`;
resultsList.appendChild(listItem);
});
formContainer.appendChild(resultsList);
}
}
function loadBooks() {
console.log('Starting to load books...');
return fetch('http://localhost:3000/admin/get-books')
.then(response => {
console.log('Received response from get-books:', response);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(books => {
console.log('Loaded books data:', books);
displayBooks(books);
return Promise.resolve(); // 显式返回一个已解决的Promise,确保外层能正确链式调用
})
.catch(error => {
console.error('Error loading books:', error);
alert('加载图书时出错:' + error.message);
return Promise.reject(error); // 出现错误时返回一个被拒绝的Promise,传播错误
});
}
function displayBooks(books) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">图书管理</h2>
<div class="book-list-container">
<ul>
`;
books.forEach(book => {
formContainer.innerHTML += `
<li>
${book.title} by ${book.author} (${book.year_published})
<button onclick="editBookForm('${book.id}')">编辑</button>
<button onclick="deleteBookConfirm('${book.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
return Promise.resolve();
code Copy code
function loadUsers() {
return fetch('http://localhost:3000/admin/get-users')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(users => {
displayUsers(users);
return users; // 将处理后的用户数据返回,使得外层能接收到这个 Promise 结果
})
.catch(error => {
console.error('Error loading users:', error);
alert('加载用户时出错:' + error.message);
throw error; // 可以选择重新抛出错误,让调用处能进一步处理
});
}
function displayUsers(users) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">用户管理</h2>
<div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
<ul style="list-style-type: none; padding: 0;">
`;
users.forEach(user => {
formContainer.innerHTML += `
<li style="margin: 10px 0;">
${user.username}
<button onclick="editUserForm('${user.id}')">编辑</button>
<button onclick="deleteUserConfirm('${user.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
}
function loadBorrowRecords() {
fetch('http://localhost:3000/admin/borrow-records')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(records => {
displayBorrowRecords(records);
})
.catch(error => {
console.error('Error loading borrow records:', error);
alert('加载借阅记录时出错:' + error.message);
});
}
function displayBorrowRecords(records) {
console.log('Borrow records:', records); // Debug log
const borrowRecordsList = document.getElementById('borrowRecordsList');
borrowRecordsList.innerHTML = ''; // 清空之前的内容
if (records.length === 0) {
borrowRecordsList.innerHTML = '<p>无借阅记录。</p>';
} else {
const table = document.createElement('table');
table.innerHTML = `
<tr>
<th>用户名</th>
<th>书名</th>
<th>作者</th>
<th>借阅日期</th>
<th>操作</th>
</tr>
`;
records.forEach(record => {
console.log('Record ID:', record.id); // Debug log
const row = document.createElement('tr');
row.innerHTML = `
<td>${record.username}</td>
<td>${record.title}</td>
<td>${record.author}</td>
<td>${record.borrow_date}</td>
<td>
<button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
</td>
`;
table.appendChild(row);
});
borrowRecordsList.appendChild(table);
}
code Copy code
function deleteUser(id) {
fetch(`http://localhost:3000/admin/delete-user`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok: ' + response.statusText);
}
return response.text();
})
.then(data => {
alert(data);
loadUsers(); // 刷新用户列表
})
.catch(error => {
console.error('Error deleting user:', error);
alert('删除用户时出现错误:' + error.message);
});
}
function editUserForm(id) {
fetch(`http://localhost:3000/admin/get-user/${id}`)
.then(response => {
if (!response.ok) {
throw new Error('获取用户信息失败,状态码:' + response.status);
}
return response.json();
})
.then(user => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<form id="editUserForm">
<input type="hidden" value="${id}" name="id">
<input type="text" placeholder="用户名" value="${user.username}" name="username">
<input type="password" placeholder="密码" name="password">
<select name="role">
<option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
<option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
</select>
<button type="button" onclick="editUser(${id})">保存</button>
</form>
`;
})
.catch(error => {
console.error('编辑用户信息获取出错:', error);
alert('获取用户信息失败,请稍后重试:' + error.message);
});
}
function editUser(id) {
const form = document.querySelector(`#editUserForm`);
if (!form || !(form instanceof HTMLFormElement)) {
console.error('Invalid form element');
return;
}
const formData = new FormData(form);
const data = Object.fromEntries(formData.entries());
// Simple validation for required fields
if (!data.username || !data.password || !data.role) {
alert('请填写所有必填字段');
return;
}
fetch(`http://localhost:3000/admin/edit-user`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
.then(response => response.text())
.then(data => {
alert(data);
loadUsers(); // 刷新用户列表
})
.catch(error => {
console.error('Error editing user:', error);
alert('编辑用户信息时出现错误,请稍后重试:' + error.message);
});
}
function editBookForm(bookId) {
// 先调用获取所有图书的后端路由以获取图书数据
fetch('http://localhost:3000/admin/get-books')
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch all books data');
}
return response.json();
})
.then(allBooks => {
// 在获取到的所有图书数据中查找对应id的图书
const targetBook = allBooks.find(book => book.id === Number(bookId));
if (!targetBook) {
alert('未找到对应图书信息,请确认图书ID是否正确');
return;
}
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2>修改图书</h2>
<input type="text" placeholder="旧书名" id="oldTitle" value="${targetBook.title}" disabled>
<input type="text" placeholder="新书名" id="newTitle">
<input type="text" placeholder="新作者" id="newAuthor">
<input type="number" placeholder="新出版年份" id="newYearPublished">
<button onclick="editBook()">保存</button>
`;
})
.catch(error => {
console.error('Error fetching book data:', error);
alert('获取图书信息失败,请稍后重试:' + error.message);
});
code Copy code
function deleteBookConfirm(bookId) {
if (!bookId) {
alert('无效的图书ID');
return;
}
if (confirm(`确定要删除图书ID为${bookId}的图书吗?此操作不可撤销!`)) {
deleteBook(bookId);
}
function deleteBook(bookId) {
if (!bookId) {
alert('无效的图书ID');
return;
}
code Copy code
fetch('http://localhost:3000/admin/delete-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ id: bookId }) // 使用书籍 ID
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Book deleted:', data);
alert('图书删除成功');
loadBooks(); // 重新加载图书列表
})
.catch(error => {
console.error('Error deleting book:', error);
alert('删除图书时出错:' + error.message);
});
function editBook() {
const newTitle = document.getElementById('newTitle').value.trim();
const newAuthor = document.getElementById('newAuthor').value.trim();
const newYearPublished = document.getElementById('newYearPublished').value.trim();
code Copy code
// 简单验证输入框是否为空
if (!newTitle || !newAuthor || !newYearPublished) {
alert('请填写所有修改信息');
return;
}
const oldTitle = document.getElementById('oldTitle').value; // 注意,没有trim(),因为oldTitle是禁用输入,不应更改
fetch('http://localhost:3000/admin/edit-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ oldTitle, newTitle, newAuthor, newYearPublished })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok: ' + response.statusText);
}
return response.text();
})
.then(data => {
console.log('Book edited:', data);
alert('图书修改成功');
showForm('dataManagement'); // 返回数据管理界面
})
.catch(error => {
console.error('Error editing book:', error);
alert('修改图书时出错:' + error.message);
});
}
function deleteBorrowRecordConfirm(recordId) {
console.log('Attempting to delete record with ID:', recordId);
if (!recordId) {
alert('无效的借阅记录ID');
return;
}
if (confirm(确定要删除借阅记录ID为${recordId}的记录吗?此操作不可撤销!)) {
deleteBorrowRecord(recordId);
}
}
function deleteBorrowRecord(recordId) {
fetch('http://localhost:3000/admin/delete-borrow-record ', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ id: recordId }) // 发送要删除记录的 ID
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Borrow record deleted:', data);
alert('借阅记录删除成功');
loadBorrowRecords(); // 重新加载借阅记录列表
})
.catch(error => {
console.error('Error deleting borrow record:', error);
alert('删除借阅记录时出错:' + error.message);
});
}
const app = express();
app.use(cors());
app.use(bodyParser.json());
// MySQL数据库连接配置
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456', // 替换为你的MySQL密码
database: 'librarysystem'
});
db.connect(err => {
if (err) {
throw err;
}
console.log('MySQL connected...');
});
// 登录路由
app.post('/login', (req, res) => {
const { username, password } = req.body;
const query = 'SELECT * FROM users WHERE username = ? AND password = ?';
db.query(query, [username, password], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
console.log("Login successful, sending response:", results[0]);
res.json(results[0]);
} else {
res.status(400).json({ error: 'Invalid login' });
}
});
});
// 注册路由
app.post('/register', (req, res) => {
const { username, password } = req.body;
// 检查用户名是否已存在
const checkUserQuery = 'SELECT * FROM users WHERE username = ?';
db.query(checkUserQuery, [username], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
// 用户名已存在
res.status(400).json({ error: 'Username already exists' });
} else {
// 用户名不存在,可以注册
const insertUserQuery = 'INSERT INTO users (username, password, role) VALUES (?, ?, ?)';
db.query(insertUserQuery, [username, password, 'user'], (err, results) => {
if (err) {
res.status(500).json({ error: 'Failed to register user' });
} else {
res.status(201).send('User registered successfully');
}
});
}
});
});
// 管理员操作路由
// 添加图书
app.post('/admin/add-book', (req, res) => {
const { title, author, year_published } = req.body;
const query = 'INSERT INTO books (title, author, year_published) VALUES (?, ?, ?)';
db.query(query, [title, author, year_published], (err, results) => {
if (err) {
console.error('Error adding book:', err);
res.status(500).json({ error: 'Failed to add book' });
} else {
res.status(200).send('Book added successfully');
}
});
});
// 删除图书
app.post('/admin/delete-book', (req, res) => {
const { id } = req.body;
code Copy code
// 确保 ID 是有效的数字
if (!id || isNaN(id)) {
res.status(400).json({ error: 'Invalid book ID format' });
return;
}
const query = 'DELETE FROM books WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error deleting book:', err);
res.status(500).json({ error: 'Failed to delete book. Error details: ' + err.message });
} else {
// 检查是否有行被删除
if (results.affectedRows > 0) {
res.send('Book deleted');
} else {
res.status(404).send('No book found with this ID');
}
}
});
// 用户操作路由
// 搜索书籍
app.post('/user/search-books', (req, res) => {
const { keyword } = req.body;
const query = SELECT * FROM books WHERE id = ? OR title LIKE ? OR author LIKE ? ;
db.query(query, [keyword, %${keyword}%, %${keyword}%], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 添加收藏
// 获取用户的收藏书籍
app.get('/user/favorites/:userId', (req, res) => {
const { userId } = req.params;
const query = SELECT b.id, b.title, b.author FROM favorites f JOIN books b ON f.book_id = b.id WHERE f.user_id = ? ;
db.query(query, [userId], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 编辑图书
app.post('/admin/edit-book', (req, res) => {
const { oldTitle, newTitle, newAuthor, newYearPublished } = req.body;
code Copy code
// 验证每个字段
if (!oldTitle || !newTitle || !newAuthor || !newYearPublished) {
return res.status(400).json({ error: '所有字段都需要填写' });
}
const query = 'UPDATE books SET title=?, author=?, year_published=? WHERE title=?';
db.query(query, [newTitle, newAuthor, newYearPublished, oldTitle], (err, results) => {
if (err) {
console.error('Error editing book:', err);
return res.status(500).json({ error: 'Failed to edit book. Error details: ' + err.message });
}
// 检查是否有行被更新
if (results.affectedRows > 0) {
res.status(200).send('Book edited successfully');
} else {
res.status(404).send('No book found with that title for editing');
}
});
});
app.post('/admin/edit-book', (req, res) => {
const { oldTitle, newTitle, newAuthor, newYearPublished } = req.body;
code Copy code
// 验证每个字段
if (!oldTitle || !newTitle || !newAuthor || !newYearPublished) {
return res.status(400).json({ error: '所有字段都需要填写' });
}
const query = 'UPDATE books SET title=?, author=?, year_published=? WHERE title=?';
db.query(query, [newTitle, newAuthor, newYearPublished, oldTitle], (err, results) => {
if (err) {
console.error('Error editing book:', err);
return res.status(500).json({ error: 'Failed to edit book. Error details: ' + err.message });
}
// 检查是否有行被更新
if (results.affectedRows > 0) {
res.status(200).send('Book edited successfully');
} else {
res.status(404).send('No book found with that title for editing');
}
});
app.get('/admin/get-books', (req, res) => {
const query = 'SELECT * FROM books';
db.query(query, (err, results) => {
if (err) {
console.error('Error getting books:', err);
res.status(500).json({ error: 'Failed to get books' });
} else {
res.json(results);
}
});
});
// 获取所有用户
app.get('/admin/get-users', (req, res) => {
const query = 'SELECT * FROM users';
db.query(query, (err, results) => {
if (err) {
console.error('Error getting users:', err);
res.status(500).json({ error: 'Failed to get users' });
} else {
res.json(results);
}
});
});
// 借阅书籍
app.post('/user/borrow-book', (req, res) => {
const { userId, bookId } = req.body;
const query = 'INSERT INTO borrow_records (user_id, book_id, borrow_date) VALUES (?, ?, NOW())';
db.query(query, [userId, bookId], (err, results) => {
if (err) {
console.error('Error borrowing book:', err);
res.status(500).json({ error: 'Failed to borrow book' });
} else {
res.status(200).send('Book borrowed successfully');
}
});
});
// 获取借阅历史
app.get('/user/borrow-history/:userId', (req, res) => {
const { userId } = req.params;
const query = SELECT b.title, b.author, br.borrow_date FROM borrow_records br JOIN books b ON br.book_id = b.id WHERE br.user_id = ? ORDER BY br.borrow_date DESC ;
db.query(query, [userId], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 获取所有借阅记录(管理员用)
app.get('/admin/borrow-records', (req, res) => {
const query = SELECT u.username, b.title, b.author, br.borrow_date FROM borrow_records br JOIN users u ON br.user_id = u.id JOIN books b ON br.book_id = b.id ORDER BY br.borrow_date DESC ;
db.query(query, (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 编辑用户
app.post('/admin/edit-user', (req, res) => {
const { id, username, password, role } = req.body;
const query = 'UPDATE users SET username =?, password =?, role =? WHERE id =?';
db.query(query, [username, password, role, id], (err, results) => {
if (err) {
console.error('编辑用户信息出错,编辑的用户ID:', id);
console.error('错误信息:', err.message);
console.error('错误堆栈:', err.stack);
res.status(500).json({ error: 'Failed to edit user' });
} else {
console.log('用户信息编辑成功,编辑的用户ID:', id);
res.status(200).send('User edited successfully');
}
});
});
// 删除用户
app.post('/admin/delete-user', (req, res) => {
const { id } = req.body;
db.beginTransaction((err => {
if (err) {
console.error('Error starting transaction:', err);
res.status(500).send('Server error starting transaction');
return;
}
// 先删除 borrow_records 表中与该用户相关的记录
const deleteBorrowRecordsQuery = 'DELETE FROM borrow_records WHERE user_id =?';
db.query(deleteBorrowRecordsQuery, [id], (err => {
if (err) {
db.rollback(() => {
console.error('Error deleting related borrow records, rolling back transaction:', err);
res.status(500).send('Server error when deleting related borrow records, transaction rolled back');
});
return;
}
// 再删除 favorites 表中与该用户相关的记录
const deleteFavoritesQuery = 'DELETE FROM favorites WHERE user_id =?';
db.query(deleteFavoritesQuery, [id], (err => {
if (err) {
db.rollback(() => {
console.error('Error deleting related favorites, rolling back transaction:', err);
res.status(500).send('Server error when deleting related favorites, transaction rolled back');
});
return;
}
// 最后执行删除用户操作
const query = 'DELETE FROM users WHERE id =?';
db.query(query, [id], (err, results) => {
if (err) {
db.rollback(() => {
console.error('删除用户出错,要删除的用户ID:', id);
console.error('错误信息:', err.message);
console.error('错误堆栈:', err.stack);
res.status(500).send('Server error, transaction rolled back');
});
} else {
db.commit((err => {
if (err) {
console.error('Error committing transaction:', err);
res.status(500).send('Server error committing transaction');
return;
}
console.log('用户删除成功,删除的用户ID:', id);
res.send('User deleted');
}));
}
});
}));
}));
}));
});
//获取单个用户
app.get('/admin/get-user/:id', (req, res) => {
const { id } = req.params;
const query = 'SELECT * FROM users WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error getting user:', err);
res.status(500).json({ error: 'Failed to get user' });
} else if (results.length === 0) {
res.status(404).json({ error: 'User not found' });
} else {
res.json(results[0]);
}
});
});
// 编辑借阅记录(注意:通常借阅记录不需要编辑,但这里为了完整性提供示例)
app.post('/admin/edit-borrow-record', (req, res) => {
const { id, user_id, book_id, borrow_date } = req.body;
const query = 'UPDATE borrow_records SET user_id = ?, book_id = ?, borrow_date = ? WHERE id = ?';
db.query(query, [user_id, book_id, borrow_date, id], (err, results) => {
if (err) {
console.error('Error editing borrow record:', err);
res.status(500).json({ error: 'Failed to edit borrow record' });
} else {
res.status(200).send('Borrow record edited successfully');
}
});
});
// 删除借阅记录
app.post('/admin/delete-borrow-record', (req, res) => {
const { id } = req.body;
code Copy code
if (!id || isNaN(id)) {
return res.status(400).send('无效的借阅记录ID格式');
}
const query = 'DELETE FROM borrow_records WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error deleting borrow record:', err);
return res.status(500).send('服务器错误');
}
if (results.affectedRows > 0) {
res.send('借阅记录删除成功');
} else {
res.status(404).send('没有找到该借阅记录');
}
});
});
// 获取单个借阅记录详情的路由
app.get('/admin/get-borrow-record/:id', (req, res) => {
const { id } = req.params;
// 验证id是否为有效的数字且大于0
if (!Number.isInteger(Number(id)) || Number(id) <= 0) {
res.status(400).json({ error: 'Invalid borrow record ID format or value' });
return;
}
const query = SELECT * FROM borrow_records WHERE id =? ;
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error getting borrow record:', err);
res.status(500).json({ error: 'Failed to get borrow record. Error details: ' + err.message });
} else if (results.length === 0) {
res.status(404).json({ error: 'Borrow record not found' });
} else {
res.json(results[0]);
}
});
});
// 添加收藏路由
app.post('/user/add-favorite', (req, res) => {
const { userId, bookId } = req.body;
// 先检查该用户是否已经收藏了这本书
const checkFavoriteQuery = 'SELECT * FROM favorites WHERE user_id =? AND book_id =?';
db.query(checkFavoriteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
// 已收藏,提示用户
res.status(400).json({ error: 'This book has already been added to favorites' });
} else {
// 可以添加收藏,插入记录到 favorites 表
const insertFavoriteQuery = 'INSERT INTO favorites (user_id, book_id) VALUES (?,?)';
db.query(insertFavoriteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Failed to add to favorites' });
} else {
// 返回成功的 JSON 响应
res.status(200).json({ message: 'Book added to favorites successfully' });
}
});
}
});
});
// 删除收藏书籍路由
app.post('/user/delete-favorite', (req, res) => {
const { userId, bookId } = req.body;
const deleteQuery = 'DELETE FROM favorites WHERE user_id =? AND book_id =?';
db.query(deleteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error when deleting favorite' });
} else if (results.affectedRows === 0) {
// 如果受影响的行数为0,表示没有找到对应的收藏记录,即可能已经不存在该收藏了
res.status(400).json({ error: 'This book is not in your favorites' });
} else {
res.status(200).json({ message: 'Book removed from favorites successfully' });
}
});
});
// 从收藏中借阅书籍
app.post('/user/borrow-from-favorite', (req, res) => {
const { userId, bookId } = req.body;
// 先从收藏中删除这本书
const deleteFavoriteQuery = 'DELETE FROM favorites WHERE user_id = ? AND book_id = ?';
db.query(deleteFavoriteQuery, [userId, bookId], (err, deleteResults) => {
if (err) {
console.error('Error deleting favorite before borrowing:', err);
res.status(500).json({ error: 'Failed to borrow book from favorites' });
return;
}
if (deleteResults.affectedRows === 0) {
res.status(400).json({ error: 'This book is not in your favorites' });
return;
}
code Copy code
// 然后借阅这本书
const borrowQuery = 'INSERT INTO borrow_records (user_id, book_id, borrow_date) VALUES (?, ?, NOW())';
db.query(borrowQuery, [userId, bookId], (err, borrowResults) => {
if (err) {
console.error('Error borrowing book:', err);
res.status(500).json({ error: 'Failed to borrow book' });
} else {
// 返回成功的 JSON 响应
res.status(200).json({ message: 'Book borrowed from favorites successfully' });
}
});
});
// 监听端口
const PORT = 3000;
app.listen(PORT, () => {
console.log(Server running on port ${PORT});
}); 修改代码,让借阅记录能够成功获取id
function displayBorrowRecords(records) {
console.log('Borrow records:', records); // Debug log
const borrowRecordsList = document.getElementById('borrowRecordsList');
borrowRecordsList.innerHTML = ''; // 清空之前的内容
if (records.length === 0) {
borrowRecordsList.innerHTML = '<p>无借阅记录。</p>';
} else {
const table = document.createElement('table');
table.innerHTML = `
<tr>
<th>用户名</th>
<th>书名</th>
<th>作者</th>
<th>借阅日期</th>
<th>操作</th>
</tr>
`;
records.forEach(record => {
console.log('Record ID:', record.id); // Debug log
const row = document.createElement('tr');
row.innerHTML = `
<td>${record.username}</td>
<td>${record.title}</td>
<td>${record.author}</td>
<td>${record.borrow_date}</td>
<td>
<button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
</td>
`;
table.appendChild(row);
});
borrowRecordsList.appendChild(table);
}
}
3. 确保数据结构 在你确保后端返回的数据格式是正确的后,再次运行前端并查看控制台输出是否能正确获取到借阅记录的 ID。如果能正确获取,接下来在删除时确保可以调用确认删除函数。
4. 测试 经过上面的修改,确保整个数据链路(从后端到前端)都是完整的。使用浏览器的开发者工具(F12)来观察网络请求和控制台信息,确保没有任何错误。
在你的应用运行时,调用 loadBorrowRecords 函数以加载借阅记录,并查看控制台输出,如果 Record ID 显示有效,则问题已解决。如果仍有问题,确保你在任何地方未修改数据结构并进行调试。
完成上述几个步骤后,你应该能够成功获取并正确显示借阅记录的 ID。
// 根据type动态创建表单
switch (type) {
case 'add':
formContainer.innerHTML = `
<input type="text" placeholder="书名">
<input type="text" placeholder="作者">
<input type="number" placeholder="出版年份">
<button onclick="addBook()">添加</button>
`;
break;
case 'delete':
formContainer.innerHTML = `
<h2>删除图书</h2>
<input type="text" id="bookTitle" placeholder="输入书名" style="width: 200px;" />
<button onclick="deleteBook()">删除</button>
`;
break;
case 'borrowRecords':
formContainer.innerHTML = `<h2>借阅记录</h2><div id="borrowRecordsList"></div>`;
loadBorrowRecords();
break;
case 'edit':
formContainer.innerHTML = `
<h2>修改图书</h2>
<input type="text" placeholder="旧书名" id="oldTitle">
<input type="text" placeholder="新书名" id="newTitle">
<input type="text" placeholder="新作者" id="newAuthor">
<input type="number" placeholder="新出版年份" id="newYearPublished">
<button onclick="editBook()">修改</button>
`;
break;
case 'search':
formContainer.innerHTML = `
<input type="text" placeholder="搜索关键词" id="searchKeyword">
<button onclick="searchBooks()">查询</button>
`;
break;
case 'userManagement':
loadUsers().then(users => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">用户管理</h2>
<div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
<ul style="list-style-type: none; padding: 0;">
`;
users.forEach(user => {
formContainer.innerHTML += `
<li style="margin: 10px 0;">
${user.username}
<button onclick="editUserForm('${user.id}')">编辑</button>
<button onclick="deleteUser('${user.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
});
break;
case 'dataManagement':
formContainer.innerHTML = `
<h2>数据管理</h2>
<!-- 这里可以添加数据管理的相关表单或内容 -->
`;
loadBooks(); // 正确的位置
break;
case 'borrowRecords':
formContainer.innerHTML = `
<h2>借阅记录</h2>
<!-- 这里可以添加借阅记录的相关表单或内容 -->
`;
break;
case 'editUser':
fetch(`http://localhost:3000/admin/get-user/${id}`)
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch user data');
}
return response.json();
})
.then(user => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<input type="hidden" value="${id}" name="id">
<input type="text" placeholder="用户名" value="${user.username}" name="username">
<input type="password" placeholder="密码" name="password">
<select name="role">
<option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
<option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
</select>
<button onclick="editUser(${id})">保存</button>
`;
})
.catch(error => {
console.error('Error fetching user data:', error);
alert('Failed to fetch user data: ' + error.message);
});
break;
case 'deleteUser':
if (confirm(`确定要删除用户ID为${id}的用户吗?此操作不可撤销!`)) {
deleteUser(id);
}
break;
default:
formContainer.style.display = 'none';
}
}
function addBook() {
// 获取表单数据
const formContainer = document.getElementById('formContainer');
const title = formContainer.querySelector('input[placeholder="书名"]').value;
const author = formContainer.querySelector('input[placeholder="作者"]').value;
const year_published = formContainer.querySelector('input[placeholder="出版年份"]').value; // 使用正确的变量名
// 发送增加图书的请求
fetch('http://localhost:3000/admin/add-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin' // 假设已经在某处设置了用户类型
},
body: JSON.stringify({ title, author, year_published }) // 使用正确的变量名
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Book added:', data);
alert('图书添加成功:' + data); // 显示成功消息
// 可选:清空表单
formContainer.innerHTML = '';
formContainer.style.display = 'none';
// 可选:更新图书列表(如果有的话)
})
.catch(error => {
console.error('Error adding book:', error);
alert('添加图书时出错:' + error.message);
});
}
function searchBooks() {
const searchKeyword = document.getElementById('searchKeyword').value;
fetch('http://localhost:3000/user/search-books', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ keyword: searchKeyword })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
displaySearchResults(data);
})
.catch(error => {
console.error('Error searching books:', error);
alert('搜索图书时出错:' + error.message);
});
}
function displaySearchResults(books) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<div>
<button onclick="showForm('search')">返回继续搜索</button>
</div>
<h2>搜索结果</h2>
`;
if (books.length === 0) {
formContainer.innerHTML += '<p>未找到图书。</p>';
} else {
const resultsList = document.createElement('ul');
books.forEach(book => {
const listItem = document.createElement('li');
listItem.textContent = `${book.title} by ${book.author} (${book.year_published})`;
resultsList.appendChild(listItem);
});
formContainer.appendChild(resultsList);
}
}
function loadBooks() {
console.log('Starting to load books...');
return fetch('http://localhost:3000/admin/get-books')
.then(response => {
console.log('Received response from get-books:', response);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(books => {
console.log('Loaded books data:', books);
displayBooks(books);
return Promise.resolve(); // 显式返回一个已解决的Promise,确保外层能正确链式调用
})
.catch(error => {
console.error('Error loading books:', error);
alert('加载图书时出错:' + error.message);
return Promise.reject(error); // 出现错误时返回一个被拒绝的Promise,传播错误
});
}
function displayBooks(books) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">图书管理</h2>
<div class="book-list-container">
<ul>
`;
books.forEach(book => {
formContainer.innerHTML += `
<li>
${book.title} by ${book.author} (${book.year_published})
<button onclick="editBookForm('${book.id}')">编辑</button>
<button onclick="deleteBookConfirm('${book.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
return Promise.resolve();
code Copy code
function loadUsers() {
return fetch('http://localhost:3000/admin/get-users')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(users => {
displayUsers(users);
return users; // 将处理后的用户数据返回,使得外层能接收到这个 Promise 结果
})
.catch(error => {
console.error('Error loading users:', error);
alert('加载用户时出错:' + error.message);
throw error; // 可以选择重新抛出错误,让调用处能进一步处理
});
}
function displayUsers(users) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">用户管理</h2>
<div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
<ul style="list-style-type: none; padding: 0;">
`;
users.forEach(user => {
formContainer.innerHTML += `
<li style="margin: 10px 0;">
${user.username}
<button onclick="editUserForm('${user.id}')">编辑</button>
<button onclick="deleteUserConfirm('${user.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
}
function loadBorrowRecords() {
fetch('http://localhost:3000/admin/borrow-records')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(records => {
displayBorrowRecords(records);
})
.catch(error => {
console.error('Error loading borrow records:', error);
alert('加载借阅记录时出错:' + error.message);
});
}
function displayBorrowRecords(records) {
console.log('Borrow records:', records); // Debug log
const borrowRecordsList = document.getElementById('borrowRecordsList');
borrowRecordsList.innerHTML = ''; // 清空之前的内容
if (records.length === 0) {
borrowRecordsList.innerHTML = '<p>无借阅记录。</p>';
} else {
const table = document.createElement('table');
table.innerHTML = `
<tr>
<th>用户名</th>
<th>书名</th>
<th>作者</th>
<th>借阅日期</th>
<th>操作</th>
</tr>
`;
records.forEach(record => {
console.log('Record ID:', record.id); // Debug log
const row = document.createElement('tr');
row.innerHTML = `
<td>${record.username}</td>
<td>${record.title}</td>
<td>${record.author}</td>
<td>${record.borrow_date}</td>
<td>
<button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
</td>
`;
table.appendChild(row);
});
borrowRecordsList.appendChild(table);
}
code Copy code
function deleteUser(id) {
fetch(`http://localhost:3000/admin/delete-user`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok: ' + response.statusText);
}
return response.text();
})
.then(data => {
alert(data);
loadUsers(); // 刷新用户列表
})
.catch(error => {
console.error('Error deleting user:', error);
alert('删除用户时出现错误:' + error.message);
});
}
function editUserForm(id) {
fetch(`http://localhost:3000/admin/get-user/${id}`)
.then(response => {
if (!response.ok) {
throw new Error('获取用户信息失败,状态码:' + response.status);
}
return response.json();
})
.then(user => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<form id="editUserForm">
<input type="hidden" value="${id}" name="id">
<input type="text" placeholder="用户名" value="${user.username}" name="username">
<input type="password" placeholder="密码" name="password">
<select name="role">
<option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
<option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
</select>
<button type="button" onclick="editUser(${id})">保存</button>
</form>
`;
})
.catch(error => {
console.error('编辑用户信息获取出错:', error);
alert('获取用户信息失败,请稍后重试:' + error.message);
});
}
function editUser(id) {
const form = document.querySelector(`#editUserForm`);
if (!form || !(form instanceof HTMLFormElement)) {
console.error('Invalid form element');
return;
}
const formData = new FormData(form);
const data = Object.fromEntries(formData.entries());
// Simple validation for required fields
if (!data.username || !data.password || !data.role) {
alert('请填写所有必填字段');
return;
}
fetch(`http://localhost:3000/admin/edit-user`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
.then(response => response.text())
.then(data => {
alert(data);
loadUsers(); // 刷新用户列表
})
.catch(error => {
console.error('Error editing user:', error);
alert('编辑用户信息时出现错误,请稍后重试:' + error.message);
});
}
function editBookForm(bookId) {
// 先调用获取所有图书的后端路由以获取图书数据
fetch('http://localhost:3000/admin/get-books')
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch all books data');
}
return response.json();
})
.then(allBooks => {
// 在获取到的所有图书数据中查找对应id的图书
const targetBook = allBooks.find(book => book.id === Number(bookId));
if (!targetBook) {
alert('未找到对应图书信息,请确认图书ID是否正确');
return;
}
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2>修改图书</h2>
<input type="text" placeholder="旧书名" id="oldTitle" value="${targetBook.title}" disabled>
<input type="text" placeholder="新书名" id="newTitle">
<input type="text" placeholder="新作者" id="newAuthor">
<input type="number" placeholder="新出版年份" id="newYearPublished">
<button onclick="editBook()">保存</button>
`;
})
.catch(error => {
console.error('Error fetching book data:', error);
alert('获取图书信息失败,请稍后重试:' + error.message);
});
code Copy code
function deleteBookConfirm(bookId) {
if (!bookId) {
alert('无效的图书ID');
return;
}
if (confirm(`确定要删除图书ID为${bookId}的图书吗?此操作不可撤销!`)) {
deleteBook(bookId);
}
function deleteBook(bookId) {
if (!bookId) {
alert('无效的图书ID');
return;
}
code Copy code
fetch('http://localhost:3000/admin/delete-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ id: bookId }) // 使用书籍 ID
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Book deleted:', data);
alert('图书删除成功');
loadBooks(); // 重新加载图书列表
})
.catch(error => {
console.error('Error deleting book:', error);
alert('删除图书时出错:' + error.message);
});
function editBook() {
const newTitle = document.getElementById('newTitle').value.trim();
const newAuthor = document.getElementById('newAuthor').value.trim();
const newYearPublished = document.getElementById('newYearPublished').value.trim();
code Copy code
// 简单验证输入框是否为空
if (!newTitle || !newAuthor || !newYearPublished) {
alert('请填写所有修改信息');
return;
}
const oldTitle = document.getElementById('oldTitle').value; // 注意,没有trim(),因为oldTitle是禁用输入,不应更改
fetch('http://localhost:3000/admin/edit-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ oldTitle, newTitle, newAuthor, newYearPublished })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok: ' + response.statusText);
}
return response.text();
})
.then(data => {
console.log('Book edited:', data);
alert('图书修改成功');
showForm('dataManagement'); // 返回数据管理界面
})
.catch(error => {
console.error('Error editing book:', error);
alert('修改图书时出错:' + error.message);
});
}
function deleteBorrowRecordConfirm(recordId) {
console.log('Attempting to delete record with ID:', recordId);
if (!recordId) {
alert('无效的借阅记录ID');
return;
}
if (confirm(确定要删除借阅记录ID为${recordId}的记录吗?此操作不可撤销!)) {
deleteBorrowRecord(recordId);
}
}
function deleteBorrowRecord(recordId) {
fetch('http://localhost:3000/admin/delete-borrow-record ', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ id: recordId }) // 发送要删除记录的 ID
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Borrow record deleted:', data);
alert('借阅记录删除成功');
loadBorrowRecords(); // 重新加载借阅记录列表
})
.catch(error => {
console.error('Error deleting borrow record:', error);
alert('删除借阅记录时出错:' + error.message);
});
}
const app = express();
app.use(cors());
app.use(bodyParser.json());
// MySQL数据库连接配置
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456', // 替换为你的MySQL密码
database: 'librarysystem'
});
db.connect(err => {
if (err) {
throw err;
}
console.log('MySQL connected...');
});
// 登录路由
app.post('/login', (req, res) => {
const { username, password } = req.body;
const query = 'SELECT * FROM users WHERE username = ? AND password = ?';
db.query(query, [username, password], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
console.log("Login successful, sending response:", results[0]);
res.json(results[0]);
} else {
res.status(400).json({ error: 'Invalid login' });
}
});
});
// 注册路由
app.post('/register', (req, res) => {
const { username, password } = req.body;
// 检查用户名是否已存在
const checkUserQuery = 'SELECT * FROM users WHERE username = ?';
db.query(checkUserQuery, [username], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
// 用户名已存在
res.status(400).json({ error: 'Username already exists' });
} else {
// 用户名不存在,可以注册
const insertUserQuery = 'INSERT INTO users (username, password, role) VALUES (?, ?, ?)';
db.query(insertUserQuery, [username, password, 'user'], (err, results) => {
if (err) {
res.status(500).json({ error: 'Failed to register user' });
} else {
res.status(201).send('User registered successfully');
}
});
}
});
});
// 管理员操作路由
// 添加图书
app.post('/admin/add-book', (req, res) => {
const { title, author, year_published } = req.body;
const query = 'INSERT INTO books (title, author, year_published) VALUES (?, ?, ?)';
db.query(query, [title, author, year_published], (err, results) => {
if (err) {
console.error('Error adding book:', err);
res.status(500).json({ error: 'Failed to add book' });
} else {
res.status(200).send('Book added successfully');
}
});
});
// 删除图书
app.post('/admin/delete-book', (req, res) => {
const { id } = req.body;
code Copy code
// 确保 ID 是有效的数字
if (!id || isNaN(id)) {
res.status(400).json({ error: 'Invalid book ID format' });
return;
}
const query = 'DELETE FROM books WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error deleting book:', err);
res.status(500).json({ error: 'Failed to delete book. Error details: ' + err.message });
} else {
// 检查是否有行被删除
if (results.affectedRows > 0) {
res.send('Book deleted');
} else {
res.status(404).send('No book found with this ID');
}
}
});
// 用户操作路由
// 搜索书籍
app.post('/user/search-books', (req, res) => {
const { keyword } = req.body;
const query = SELECT * FROM books WHERE id = ? OR title LIKE ? OR author LIKE ? ;
db.query(query, [keyword, %${keyword}%, %${keyword}%], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 添加收藏
// 获取用户的收藏书籍
app.get('/user/favorites/:userId', (req, res) => {
const { userId } = req.params;
const query = SELECT b.id, b.title, b.author FROM favorites f JOIN books b ON f.book_id = b.id WHERE f.user_id = ? ;
db.query(query, [userId], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 编辑图书
app.post('/admin/edit-book', (req, res) => {
const { oldTitle, newTitle, newAuthor, newYearPublished } = req.body;
code Copy code
// 验证每个字段
if (!oldTitle || !newTitle || !newAuthor || !newYearPublished) {
return res.status(400).json({ error: '所有字段都需要填写' });
}
const query = 'UPDATE books SET title=?, author=?, year_published=? WHERE title=?';
db.query(query, [newTitle, newAuthor, newYearPublished, oldTitle], (err, results) => {
if (err) {
console.error('Error editing book:', err);
return res.status(500).json({ error: 'Failed to edit book. Error details: ' + err.message });
}
// 检查是否有行被更新
if (results.affectedRows > 0) {
res.status(200).send('Book edited successfully');
} else {
res.status(404).send('No book found with that title for editing');
}
});
});
app.post('/admin/edit-book', (req, res) => {
const { oldTitle, newTitle, newAuthor, newYearPublished } = req.body;
code Copy code
// 验证每个字段
if (!oldTitle || !newTitle || !newAuthor || !newYearPublished) {
return res.status(400).json({ error: '所有字段都需要填写' });
}
const query = 'UPDATE books SET title=?, author=?, year_published=? WHERE title=?';
db.query(query, [newTitle, newAuthor, newYearPublished, oldTitle], (err, results) => {
if (err) {
console.error('Error editing book:', err);
return res.status(500).json({ error: 'Failed to edit book. Error details: ' + err.message });
}
// 检查是否有行被更新
if (results.affectedRows > 0) {
res.status(200).send('Book edited successfully');
} else {
res.status(404).send('No book found with that title for editing');
}
});
app.get('/admin/get-books', (req, res) => {
const query = 'SELECT * FROM books';
db.query(query, (err, results) => {
if (err) {
console.error('Error getting books:', err);
res.status(500).json({ error: 'Failed to get books' });
} else {
res.json(results);
}
});
});
// 获取所有用户
app.get('/admin/get-users', (req, res) => {
const query = 'SELECT * FROM users';
db.query(query, (err, results) => {
if (err) {
console.error('Error getting users:', err);
res.status(500).json({ error: 'Failed to get users' });
} else {
res.json(results);
}
});
});
// 借阅书籍
app.post('/user/borrow-book', (req, res) => {
const { userId, bookId } = req.body;
const query = 'INSERT INTO borrow_records (user_id, book_id, borrow_date) VALUES (?, ?, NOW())';
db.query(query, [userId, bookId], (err, results) => {
if (err) {
console.error('Error borrowing book:', err);
res.status(500).json({ error: 'Failed to borrow book' });
} else {
res.status(200).send('Book borrowed successfully');
}
});
});
// 获取借阅历史
app.get('/user/borrow-history/:userId', (req, res) => {
const { userId } = req.params;
const query = SELECT b.title, b.author, br.borrow_date FROM borrow_records br JOIN books b ON br.book_id = b.id WHERE br.user_id = ? ORDER BY br.borrow_date DESC ;
db.query(query, [userId], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 获取所有借阅记录(管理员用)
// 获取所有借阅记录(管理员用)
app.get('/admin/borrow-records', (req, res) => {
const query = SELECT br.id, u.username, b.title, b.author, br.borrow_date FROM borrow_records br JOIN users u ON br.user_id = u.id JOIN books b ON br.book_id = b.id ORDER BY br.borrow_date DESC ;
db.query(query, (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
// Ensure that the ID is included in results
res.json(results);
}
});
});
// 编辑用户
app.post('/admin/edit-user', (req, res) => {
const { id, username, password, role } = req.body;
const query = 'UPDATE users SET username =?, password =?, role =? WHERE id =?';
db.query(query, [username, password, role, id], (err, results) => {
if (err) {
console.error('编辑用户信息出错,编辑的用户ID:', id);
console.error('错误信息:', err.message);
console.error('错误堆栈:', err.stack);
res.status(500).json({ error: 'Failed to edit user' });
} else {
console.log('用户信息编辑成功,编辑的用户ID:', id);
res.status(200).send('User edited successfully');
}
});
});
// 删除用户
app.post('/admin/delete-user', (req, res) => {
const { id } = req.body;
db.beginTransaction((err => {
if (err) {
console.error('Error starting transaction:', err);
res.status(500).send('Server error starting transaction');
return;
}
// 先删除 borrow_records 表中与该用户相关的记录
const deleteBorrowRecordsQuery = 'DELETE FROM borrow_records WHERE user_id =?';
db.query(deleteBorrowRecordsQuery, [id], (err => {
if (err) {
db.rollback(() => {
console.error('Error deleting related borrow records, rolling back transaction:', err);
res.status(500).send('Server error when deleting related borrow records, transaction rolled back');
});
return;
}
// 再删除 favorites 表中与该用户相关的记录
const deleteFavoritesQuery = 'DELETE FROM favorites WHERE user_id =?';
db.query(deleteFavoritesQuery, [id], (err => {
if (err) {
db.rollback(() => {
console.error('Error deleting related favorites, rolling back transaction:', err);
res.status(500).send('Server error when deleting related favorites, transaction rolled back');
});
return;
}
// 最后执行删除用户操作
const query = 'DELETE FROM users WHERE id =?';
db.query(query, [id], (err, results) => {
if (err) {
db.rollback(() => {
console.error('删除用户出错,要删除的用户ID:', id);
console.error('错误信息:', err.message);
console.error('错误堆栈:', err.stack);
res.status(500).send('Server error, transaction rolled back');
});
} else {
db.commit((err => {
if (err) {
console.error('Error committing transaction:', err);
res.status(500).send('Server error committing transaction');
return;
}
console.log('用户删除成功,删除的用户ID:', id);
res.send('User deleted');
}));
}
});
}));
}));
}));
});
//获取单个用户
app.get('/admin/get-user/:id', (req, res) => {
const { id } = req.params;
const query = 'SELECT * FROM users WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error getting user:', err);
res.status(500).json({ error: 'Failed to get user' });
} else if (results.length === 0) {
res.status(404).json({ error: 'User not found' });
} else {
res.json(results[0]);
}
});
});
// 编辑借阅记录(注意:通常借阅记录不需要编辑,但这里为了完整性提供示例)
app.post('/admin/edit-borrow-record', (req, res) => {
const { id, user_id, book_id, borrow_date } = req.body;
const query = 'UPDATE borrow_records SET user_id = ?, book_id = ?, borrow_date = ? WHERE id = ?';
db.query(query, [user_id, book_id, borrow_date, id], (err, results) => {
if (err) {
console.error('Error editing borrow record:', err);
res.status(500).json({ error: 'Failed to edit borrow record' });
} else {
res.status(200).send('Borrow record edited successfully');
}
});
});
// 删除借阅记录
app.post('/admin/delete-borrow-record', (req, res) => {
const { id } = req.body;
code Copy code
if (!id || isNaN(id)) {
return res.status(400).send('无效的借阅记录ID格式');
}
const query = 'DELETE FROM borrow_records WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error deleting borrow record:', err);
return res.status(500).send('服务器错误');
}
if (results.affectedRows > 0) {
res.send('借阅记录删除成功');
} else {
res.status(404).send('没有找到该借阅记录');
}
});
});
// 获取单个借阅记录详情的路由
app.get('/admin/get-borrow-record/:id', (req, res) => {
const { id } = req.params;
// 验证id是否为有效的数字且大于0
if (!Number.isInteger(Number(id)) || Number(id) <= 0) {
res.status(400).json({ error: 'Invalid borrow record ID format or value' });
return;
}
const query = SELECT * FROM borrow_records WHERE id =? ;
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error getting borrow record:', err);
res.status(500).json({ error: 'Failed to get borrow record. Error details: ' + err.message });
} else if (results.length === 0) {
res.status(404).json({ error: 'Borrow record not found' });
} else {
res.json(results[0]);
}
});
});
// 添加收藏路由
app.post('/user/add-favorite', (req, res) => {
const { userId, bookId } = req.body;
// 先检查该用户是否已经收藏了这本书
const checkFavoriteQuery = 'SELECT * FROM favorites WHERE user_id =? AND book_id =?';
db.query(checkFavoriteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
// 已收藏,提示用户
res.status(400).json({ error: 'This book has already been added to favorites' });
} else {
// 可以添加收藏,插入记录到 favorites 表
const insertFavoriteQuery = 'INSERT INTO favorites (user_id, book_id) VALUES (?,?)';
db.query(insertFavoriteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Failed to add to favorites' });
} else {
// 返回成功的 JSON 响应
res.status(200).json({ message: 'Book added to favorites successfully' });
}
});
}
});
});
// 删除收藏书籍路由
app.post('/user/delete-favorite', (req, res) => {
const { userId, bookId } = req.body;
const deleteQuery = 'DELETE FROM favorites WHERE user_id =? AND book_id =?';
db.query(deleteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error when deleting favorite' });
} else if (results.affectedRows === 0) {
// 如果受影响的行数为0,表示没有找到对应的收藏记录,即可能已经不存在该收藏了
res.status(400).json({ error: 'This book is not in your favorites' });
} else {
res.status(200).json({ message: 'Book removed from favorites successfully' });
}
});
});
// 从收藏中借阅书籍
app.post('/user/borrow-from-favorite', (req, res) => {
const { userId, bookId } = req.body;
// 先从收藏中删除这本书
const deleteFavoriteQuery = 'DELETE FROM favorites WHERE user_id = ? AND book_id = ?';
db.query(deleteFavoriteQuery, [userId, bookId], (err, deleteResults) => {
if (err) {
console.error('Error deleting favorite before borrowing:', err);
res.status(500).json({ error: 'Failed to borrow book from favorites' });
return;
}
if (deleteResults.affectedRows === 0) {
res.status(400).json({ error: 'This book is not in your favorites' });
return;
}
code Copy code
// 然后借阅这本书
const borrowQuery = 'INSERT INTO borrow_records (user_id, book_id, borrow_date) VALUES (?, ?, NOW())';
db.query(borrowQuery, [userId, bookId], (err, borrowResults) => {
if (err) {
console.error('Error borrowing book:', err);
res.status(500).json({ error: 'Failed to borrow book' });
} else {
// 返回成功的 JSON 响应
res.status(200).json({ message: 'Book borrowed from favorites successfully' });
}
});
});
// 监听端口
const PORT = 3000;
app.listen(PORT, () => {
console.log(Server running on port ${PORT});
}); CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
role ENUM('user', 'admin') NOT NULL
);
CREATE TABLE books (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(100) NOT NULL,
author VARCHAR(100) NOT NULL,
year_published INT
);
CREATE TABLE borrow_records (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
book_id INT,
borrow_date DATE,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (book_id) REFERENCES books(id)
);
CREATE TABLE favorites (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
book_id INT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (book_id) REFERENCES books(id)
);
ALTER TABLE books MODIFY COLUMN id INT AUTO_INCREMENT;
ALTER TABLE users MODIFY COLUMN id INT AUTO_INCREMENT;
ALTER TABLE borrow_records MODIFY COLUMN id INT AUTO_INCREMENT;
ALTER TABLE favorites MODIFY COLUMN id INT AUTO_INCREMENT;
SELECT * FROM borrow_records;
ALTER TABLE borrow_records ADD COLUMN return_date DATE;
code Copy code
SELECT
TABLE_NAME,
COLUMN_NAME,
CONSTRAINT_NAME
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
REFERENCED_TABLE_NAME = 'users'
AND REFERENCED_COLUMN_NAME = 'id'
AND TABLE_NAME = 'borrow_records';
ALTER TABLE borrow_records
DROP FOREIGN KEY borrow_records_ibfk_1;
ALTER TABLE borrow_records
ADD CONSTRAINT borrow_records_user_id_foreign_key
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE;
SELECT
TABLE_NAME,
COLUMN_NAME,
CONSTRAINT_NAME
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
REFERENCED_TABLE_NAME = 'users'
AND REFERENCED_COLUMN_NAME = 'id'
AND TABLE_NAME = 'favorites';
code Copy code
ALTER TABLE favorites
DROP FOREIGN KEY favorites_ibfk_1;
ALTER TABLE favorites
ADD CONSTRAINT favorites_user_id_foreign_key
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE;
ALTER TABLE borrow_records ADD COLUMN IF NOT EXISTS return_date DATE;
ALTER TABLE borrow_records ADD COLUMN returned BOOLEAN DEFAULT FALSE;
function displayBorrowRecords(records) {
console.log('Borrow records:', records); // Debug log - 确保调用时返回记录的结构
const borrowRecordsList = document.getElementById('borrowRecordsList');
borrowRecordsList.innerHTML = ''; // 清空之前的内容
if (records.length === 0) {
borrowRecordsList.innerHTML = '<p>无借阅记录。</p>';
} else {
const table = document.createElement('table');
table.innerHTML = `
<tr>
<th>用户名</th>
<th>书名</th>
<th>作者</th>
<th>借阅日期</th>
<th>操作</th>
</tr>
`;
records.forEach(record => {
console.log('Record:', record); // 输出每一条记录
const row = document.createElement('tr');
row.innerHTML = `
<td>${record.username}</td>
<td>${record.title}</td>
<td>${record.author}</td>
<td>${record.borrow_date}</td>
<td>
<button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
</td>
`;
table.appendChild(row);
});
borrowRecordsList.appendChild(table);
}
}
4. 确保正确的数据库结构 你已经在数据库中创建了 borrow_records 表,并且这个表中包含 id 字段。其中 id 字段应该是 AUTO_INCREMENT 类型,确保在插入记录时会自动生成。
sql Copy code
CREATE TABLE borrow_records (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
book_id INT,
borrow_date DATE,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (book_id) REFERENCES books(id)
);
5. 确保 API 正常返回数据 确保 /admin/borrow-records 的 API 正常运行且能返回有效的 JSON 结果。你可以使用 Postman 或 CURL 进行手动请求测试,查看返回的数据结构。
总结
检查数据库 确保数据结构正确且包含 id 字段。
查看 API 的返回值 直接从数据库查询,查看是否能得到 id。
添加调试信息 在前端代码中查看API返回的数据结构是否包含 id。
如果检查完这些仍出现问题,请提供 API 返回的数据结构样本,以及在数据库中执行查询的结果,以便更深入地检查问题。
// 根据type动态创建表单
switch (type) {
case 'add':
formContainer.innerHTML = `
<input type="text" placeholder="书名">
<input type="text" placeholder="作者">
<input type="number" placeholder="出版年份">
<button onclick="addBook()">添加</button>
`;
break;
case 'delete':
formContainer.innerHTML = `
<h2>删除图书</h2>
<input type="text" id="bookTitle" placeholder="输入书名" style="width: 200px;" />
<button onclick="deleteBook()">删除</button>
`;
break;
case 'borrowRecords':
formContainer.innerHTML = `<h2>借阅记录</h2><div id="borrowRecordsList"></div>`;
loadBorrowRecords();
break;
case 'edit':
formContainer.innerHTML = `
<h2>修改图书</h2>
<input type="text" placeholder="旧书名" id="oldTitle">
<input type="text" placeholder="新书名" id="newTitle">
<input type="text" placeholder="新作者" id="newAuthor">
<input type="number" placeholder="新出版年份" id="newYearPublished">
<button onclick="editBook()">修改</button>
`;
break;
case 'search':
formContainer.innerHTML = `
<input type="text" placeholder="搜索关键词" id="searchKeyword">
<button onclick="searchBooks()">查询</button>
`;
break;
case 'userManagement':
loadUsers().then(users => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">用户管理</h2>
<div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
<ul style="list-style-type: none; padding: 0;">
`;
users.forEach(user => {
formContainer.innerHTML += `
<li style="margin: 10px 0;">
${user.username}
<button onclick="editUserForm('${user.id}')">编辑</button>
<button onclick="deleteUser('${user.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
});
break;
case 'dataManagement':
formContainer.innerHTML = `
<h2>数据管理</h2>
<!-- 这里可以添加数据管理的相关表单或内容 -->
`;
loadBooks(); // 正确的位置
break;
case 'borrowRecords':
formContainer.innerHTML = `
<h2>借阅记录</h2>
<!-- 这里可以添加借阅记录的相关表单或内容 -->
`;
break;
case 'editUser':
fetch(`http://localhost:3000/admin/get-user/${id}`)
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch user data');
}
return response.json();
})
.then(user => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<input type="hidden" value="${id}" name="id">
<input type="text" placeholder="用户名" value="${user.username}" name="username">
<input type="password" placeholder="密码" name="password">
<select name="role">
<option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
<option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
</select>
<button onclick="editUser(${id})">保存</button>
`;
})
.catch(error => {
console.error('Error fetching user data:', error);
alert('Failed to fetch user data: ' + error.message);
});
break;
case 'deleteUser':
if (confirm(`确定要删除用户ID为${id}的用户吗?此操作不可撤销!`)) {
deleteUser(id);
}
break;
default:
formContainer.style.display = 'none';
}
}
function addBook() {
// 获取表单数据
const formContainer = document.getElementById('formContainer');
const title = formContainer.querySelector('input[placeholder="书名"]').value;
const author = formContainer.querySelector('input[placeholder="作者"]').value;
const year_published = formContainer.querySelector('input[placeholder="出版年份"]').value; // 使用正确的变量名
// 发送增加图书的请求
fetch('http://localhost:3000/admin/add-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin' // 假设已经在某处设置了用户类型
},
body: JSON.stringify({ title, author, year_published }) // 使用正确的变量名
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Book added:', data);
alert('图书添加成功:' + data); // 显示成功消息
// 可选:清空表单
formContainer.innerHTML = '';
formContainer.style.display = 'none';
// 可选:更新图书列表(如果有的话)
})
.catch(error => {
console.error('Error adding book:', error);
alert('添加图书时出错:' + error.message);
});
}
function searchBooks() {
const searchKeyword = document.getElementById('searchKeyword').value;
fetch('http://localhost:3000/user/search-books', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ keyword: searchKeyword })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
displaySearchResults(data);
})
.catch(error => {
console.error('Error searching books:', error);
alert('搜索图书时出错:' + error.message);
});
}
function displaySearchResults(books) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<div>
<button onclick="showForm('search')">返回继续搜索</button>
</div>
<h2>搜索结果</h2>
`;
if (books.length === 0) {
formContainer.innerHTML += '<p>未找到图书。</p>';
} else {
const resultsList = document.createElement('ul');
books.forEach(book => {
const listItem = document.createElement('li');
listItem.textContent = `${book.title} by ${book.author} (${book.year_published})`;
resultsList.appendChild(listItem);
});
formContainer.appendChild(resultsList);
}
}
function loadBooks() {
console.log('Starting to load books...');
return fetch('http://localhost:3000/admin/get-books')
.then(response => {
console.log('Received response from get-books:', response);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(books => {
console.log('Loaded books data:', books);
displayBooks(books);
return Promise.resolve(); // 显式返回一个已解决的Promise,确保外层能正确链式调用
})
.catch(error => {
console.error('Error loading books:', error);
alert('加载图书时出错:' + error.message);
return Promise.reject(error); // 出现错误时返回一个被拒绝的Promise,传播错误
});
}
function displayBooks(books) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">图书管理</h2>
<div class="book-list-container">
<ul>
`;
books.forEach(book => {
formContainer.innerHTML += `
<li>
${book.title} by ${book.author} (${book.year_published})
<button onclick="editBookForm('${book.id}')">编辑</button>
<button onclick="deleteBookConfirm('${book.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
return Promise.resolve();
code Copy code
function loadUsers() {
return fetch('http://localhost:3000/admin/get-users')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(users => {
displayUsers(users);
return users; // 将处理后的用户数据返回,使得外层能接收到这个 Promise 结果
})
.catch(error => {
console.error('Error loading users:', error);
alert('加载用户时出错:' + error.message);
throw error; // 可以选择重新抛出错误,让调用处能进一步处理
});
}
function displayUsers(users) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">用户管理</h2>
<div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
<ul style="list-style-type: none; padding: 0;">
`;
users.forEach(user => {
formContainer.innerHTML += `
<li style="margin: 10px 0;">
${user.username}
<button onclick="editUserForm('${user.id}')">编辑</button>
<button onclick="deleteUserConfirm('${user.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
}
function loadBorrowRecords() {
fetch('http://localhost:3000/admin/borrow-records') // 确保此 API 地址是正确的
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(records => {
console.log('Loaded borrow records:', records); // 检查返回的 records
displayBorrowRecords(records);
})
.catch(error => {
console.error('Error loading borrow records:', error);
alert('加载借阅记录时出错:' + error.message);
});
function displayBorrowRecords(records) {
console.log('Borrow records:', records); // Debug log - 确保调用时返回记录的结构
code Copy code
const borrowRecordsList = document.getElementById('borrowRecordsList');
borrowRecordsList.innerHTML = ''; // 清空之前的内容
if (records.length === 0) {
borrowRecordsList.innerHTML = '<p>无借阅记录。</p>';
} else {
const table = document.createElement('table');
table.innerHTML = `
<tr>
<th>用户名</th>
<th>书名</th>
<th>作者</th>
<th>借阅日期</th>
<th>操作</th>
</tr>
`;
records.forEach(record => {
console.log('Record:', record); // 输出每一条记录
const row = document.createElement('tr');
row.innerHTML = `
<td>${record.username}</td>
<td>${record.title}</td>
<td>${record.author}</td>
<td>${record.borrow_date}</td>
<td>
<button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
</td>
`;
table.appendChild(row);
});
borrowRecordsList.appendChild(table);
}
code Copy code
function deleteUser(id) {
fetch(`http://localhost:3000/admin/delete-user`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok: ' + response.statusText);
}
return response.text();
})
.then(data => {
alert(data);
loadUsers(); // 刷新用户列表
})
.catch(error => {
console.error('Error deleting user:', error);
alert('删除用户时出现错误:' + error.message);
});
}
function editUserForm(id) {
fetch(`http://localhost:3000/admin/get-user/${id}`)
.then(response => {
if (!response.ok) {
throw new Error('获取用户信息失败,状态码:' + response.status);
}
return response.json();
})
.then(user => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<form id="editUserForm">
<input type="hidden" value="${id}" name="id">
<input type="text" placeholder="用户名" value="${user.username}" name="username">
<input type="password" placeholder="密码" name="password">
<select name="role">
<option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
<option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
</select>
<button type="button" onclick="editUser(${id})">保存</button>
</form>
`;
})
.catch(error => {
console.error('编辑用户信息获取出错:', error);
alert('获取用户信息失败,请稍后重试:' + error.message);
});
}
function editUser(id) {
const form = document.querySelector(`#editUserForm`);
if (!form || !(form instanceof HTMLFormElement)) {
console.error('Invalid form element');
return;
}
const formData = new FormData(form);
const data = Object.fromEntries(formData.entries());
// Simple validation for required fields
if (!data.username || !data.password || !data.role) {
alert('请填写所有必填字段');
return;
}
fetch(`http://localhost:3000/admin/edit-user`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
.then(response => response.text())
.then(data => {
alert(data);
loadUsers(); // 刷新用户列表
})
.catch(error => {
console.error('Error editing user:', error);
alert('编辑用户信息时出现错误,请稍后重试:' + error.message);
});
}
function editBookForm(bookId) {
// 先调用获取所有图书的后端路由以获取图书数据
fetch('http://localhost:3000/admin/get-books')
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch all books data');
}
return response.json();
})
.then(allBooks => {
// 在获取到的所有图书数据中查找对应id的图书
const targetBook = allBooks.find(book => book.id === Number(bookId));
if (!targetBook) {
alert('未找到对应图书信息,请确认图书ID是否正确');
return;
}
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2>修改图书</h2>
<input type="text" placeholder="旧书名" id="oldTitle" value="${targetBook.title}" disabled>
<input type="text" placeholder="新书名" id="newTitle">
<input type="text" placeholder="新作者" id="newAuthor">
<input type="number" placeholder="新出版年份" id="newYearPublished">
<button onclick="editBook()">保存</button>
`;
})
.catch(error => {
console.error('Error fetching book data:', error);
alert('获取图书信息失败,请稍后重试:' + error.message);
});
code Copy code
function deleteBookConfirm(bookId) {
if (!bookId) {
alert('无效的图书ID');
return;
}
if (confirm(`确定要删除图书ID为${bookId}的图书吗?此操作不可撤销!`)) {
deleteBook(bookId);
}
function deleteBook(bookId) {
if (!bookId) {
alert('无效的图书ID');
return;
}
code Copy code
fetch('http://localhost:3000/admin/delete-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ id: bookId }) // 使用书籍 ID
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Book deleted:', data);
alert('图书删除成功');
loadBooks(); // 重新加载图书列表
})
.catch(error => {
console.error('Error deleting book:', error);
alert('删除图书时出错:' + error.message);
});
function editBook() {
const newTitle = document.getElementById('newTitle').value.trim();
const newAuthor = document.getElementById('newAuthor').value.trim();
const newYearPublished = document.getElementById('newYearPublished').value.trim();
code Copy code
// 简单验证输入框是否为空
if (!newTitle || !newAuthor || !newYearPublished) {
alert('请填写所有修改信息');
return;
}
const oldTitle = document.getElementById('oldTitle').value; // 注意,没有trim(),因为oldTitle是禁用输入,不应更改
fetch('http://localhost:3000/admin/edit-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ oldTitle, newTitle, newAuthor, newYearPublished })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok: ' + response.statusText);
}
return response.text();
})
.then(data => {
console.log('Book edited:', data);
alert('图书修改成功');
showForm('dataManagement'); // 返回数据管理界面
})
.catch(error => {
console.error('Error editing book:', error);
alert('修改图书时出错:' + error.message);
});
}
function deleteBorrowRecordConfirm(recordId) {
console.log('Attempting to delete record with ID:', recordId);
if (!recordId) {
alert('无效的借阅记录ID');
return;
}
if (confirm(确定要删除借阅记录ID为${recordId}的记录吗?此操作不可撤销!)) {
deleteBorrowRecord(recordId);
}
}
function deleteBorrowRecord(recordId) {
fetch('http://localhost:3000/admin/delete-borrow-record ', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ id: recordId }) // 发送要删除记录的 ID
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Borrow record deleted:', data);
alert('借阅记录删除成功');
loadBorrowRecords(); // 重新加载借阅记录列表
})
.catch(error => {
console.error('Error deleting borrow record:', error);
alert('删除借阅记录时出错:' + error.message);
});
}
const app = express();
app.use(cors());
app.use(bodyParser.json());
// MySQL数据库连接配置
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456', // 替换为你的MySQL密码
database: 'librarysystem'
});
db.connect(err => {
if (err) {
throw err;
}
console.log('MySQL connected...');
});
// 登录路由
app.post('/login', (req, res) => {
const { username, password } = req.body;
const query = 'SELECT * FROM users WHERE username = ? AND password = ?';
db.query(query, [username, password], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
console.log("Login successful, sending response:", results[0]);
res.json(results[0]);
} else {
res.status(400).json({ error: 'Invalid login' });
}
});
});
// 注册路由
app.post('/register', (req, res) => {
const { username, password } = req.body;
// 检查用户名是否已存在
const checkUserQuery = 'SELECT * FROM users WHERE username = ?';
db.query(checkUserQuery, [username], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
// 用户名已存在
res.status(400).json({ error: 'Username already exists' });
} else {
// 用户名不存在,可以注册
const insertUserQuery = 'INSERT INTO users (username, password, role) VALUES (?, ?, ?)';
db.query(insertUserQuery, [username, password, 'user'], (err, results) => {
if (err) {
res.status(500).json({ error: 'Failed to register user' });
} else {
res.status(201).send('User registered successfully');
}
});
}
});
});
// 管理员操作路由
// 添加图书
app.post('/admin/add-book', (req, res) => {
const { title, author, year_published } = req.body;
const query = 'INSERT INTO books (title, author, year_published) VALUES (?, ?, ?)';
db.query(query, [title, author, year_published], (err, results) => {
if (err) {
console.error('Error adding book:', err);
res.status(500).json({ error: 'Failed to add book' });
} else {
res.status(200).send('Book added successfully');
}
});
});
// 删除图书
app.post('/admin/delete-book', (req, res) => {
const { id } = req.body;
code Copy code
// 确保 ID 是有效的数字
if (!id || isNaN(id)) {
res.status(400).json({ error: 'Invalid book ID format' });
return;
}
const query = 'DELETE FROM books WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error deleting book:', err);
res.status(500).json({ error: 'Failed to delete book. Error details: ' + err.message });
} else {
// 检查是否有行被删除
if (results.affectedRows > 0) {
res.send('Book deleted');
} else {
res.status(404).send('No book found with this ID');
}
}
});
// 用户操作路由
// 搜索书籍
app.post('/user/search-books', (req, res) => {
const { keyword } = req.body;
const query = SELECT * FROM books WHERE id = ? OR title LIKE ? OR author LIKE ? ;
db.query(query, [keyword, %${keyword}%, %${keyword}%], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 添加收藏
// 获取用户的收藏书籍
app.get('/user/favorites/:userId', (req, res) => {
const { userId } = req.params;
const query = SELECT b.id, b.title, b.author FROM favorites f JOIN books b ON f.book_id = b.id WHERE f.user_id = ? ;
db.query(query, [userId], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 编辑图书
app.post('/admin/edit-book', (req, res) => {
const { oldTitle, newTitle, newAuthor, newYearPublished } = req.body;
code Copy code
// 验证每个字段
if (!oldTitle || !newTitle || !newAuthor || !newYearPublished) {
return res.status(400).json({ error: '所有字段都需要填写' });
}
const query = 'UPDATE books SET title=?, author=?, year_published=? WHERE title=?';
db.query(query, [newTitle, newAuthor, newYearPublished, oldTitle], (err, results) => {
if (err) {
console.error('Error editing book:', err);
return res.status(500).json({ error: 'Failed to edit book. Error details: ' + err.message });
}
// 检查是否有行被更新
if (results.affectedRows > 0) {
res.status(200).send('Book edited successfully');
} else {
res.status(404).send('No book found with that title for editing');
}
});
});
app.post('/admin/edit-book', (req, res) => {
const { oldTitle, newTitle, newAuthor, newYearPublished } = req.body;
code Copy code
// 验证每个字段
if (!oldTitle || !newTitle || !newAuthor || !newYearPublished) {
return res.status(400).json({ error: '所有字段都需要填写' });
}
const query = 'UPDATE books SET title=?, author=?, year_published=? WHERE title=?';
db.query(query, [newTitle, newAuthor, newYearPublished, oldTitle], (err, results) => {
if (err) {
console.error('Error editing book:', err);
return res.status(500).json({ error: 'Failed to edit book. Error details: ' + err.message });
}
// 检查是否有行被更新
if (results.affectedRows > 0) {
res.status(200).send('Book edited successfully');
} else {
res.status(404).send('No book found with that title for editing');
}
});
app.get('/admin/get-books', (req, res) => {
const query = 'SELECT * FROM books';
db.query(query, (err, results) => {
if (err) {
console.error('Error getting books:', err);
res.status(500).json({ error: 'Failed to get books' });
} else {
res.json(results);
}
});
});
// 获取所有用户
app.get('/admin/get-users', (req, res) => {
const query = 'SELECT * FROM users';
db.query(query, (err, results) => {
if (err) {
console.error('Error getting users:', err);
res.status(500).json({ error: 'Failed to get users' });
} else {
res.json(results);
}
});
});
// 借阅书籍
app.post('/user/borrow-book', (req, res) => {
const { userId, bookId } = req.body;
const query = 'INSERT INTO borrow_records (user_id, book_id, borrow_date) VALUES (?, ?, NOW())';
db.query(query, [userId, bookId], (err, results) => {
if (err) {
console.error('Error borrowing book:', err);
res.status(500).json({ error: 'Failed to borrow book' });
} else {
res.status(200).send('Book borrowed successfully');
}
});
});
// 获取借阅历史
app.get('/user/borrow-history/:userId', (req, res) => {
const { userId } = req.params;
const query = SELECT b.title, b.author, br.borrow_date FROM borrow_records br JOIN books b ON br.book_id = b.id WHERE br.user_id = ? ORDER BY br.borrow_date DESC ;
db.query(query, [userId], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 获取所有借阅记录(管理员用)
// 获取所有借阅记录(管理员用)
app.get('/admin/borrow-records', (req, res) => {
const query = SELECT br.id, u.username, b.title, b.author, br.borrow_date FROM borrow_records br JOIN users u ON br.user_id = u.id JOIN books b ON br.book_id = b.id ORDER BY br.borrow_date DESC ;
db.query(query, (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
// Ensure that the ID is included in results
res.json(results);
}
});
});
// 编辑用户
app.post('/admin/edit-user', (req, res) => {
const { id, username, password, role } = req.body;
const query = 'UPDATE users SET username =?, password =?, role =? WHERE id =?';
db.query(query, [username, password, role, id], (err, results) => {
if (err) {
console.error('编辑用户信息出错,编辑的用户ID:', id);
console.error('错误信息:', err.message);
console.error('错误堆栈:', err.stack);
res.status(500).json({ error: 'Failed to edit user' });
} else {
console.log('用户信息编辑成功,编辑的用户ID:', id);
res.status(200).send('User edited successfully');
}
});
});
// 删除用户
app.post('/admin/delete-user', (req, res) => {
const { id } = req.body;
db.beginTransaction((err => {
if (err) {
console.error('Error starting transaction:', err);
res.status(500).send('Server error starting transaction');
return;
}
// 先删除 borrow_records 表中与该用户相关的记录
const deleteBorrowRecordsQuery = 'DELETE FROM borrow_records WHERE user_id =?';
db.query(deleteBorrowRecordsQuery, [id], (err => {
if (err) {
db.rollback(() => {
console.error('Error deleting related borrow records, rolling back transaction:', err);
res.status(500).send('Server error when deleting related borrow records, transaction rolled back');
});
return;
}
// 再删除 favorites 表中与该用户相关的记录
const deleteFavoritesQuery = 'DELETE FROM favorites WHERE user_id =?';
db.query(deleteFavoritesQuery, [id], (err => {
if (err) {
db.rollback(() => {
console.error('Error deleting related favorites, rolling back transaction:', err);
res.status(500).send('Server error when deleting related favorites, transaction rolled back');
});
return;
}
// 最后执行删除用户操作
const query = 'DELETE FROM users WHERE id =?';
db.query(query, [id], (err, results) => {
if (err) {
db.rollback(() => {
console.error('删除用户出错,要删除的用户ID:', id);
console.error('错误信息:', err.message);
console.error('错误堆栈:', err.stack);
res.status(500).send('Server error, transaction rolled back');
});
} else {
db.commit((err => {
if (err) {
console.error('Error committing transaction:', err);
res.status(500).send('Server error committing transaction');
return;
}
console.log('用户删除成功,删除的用户ID:', id);
res.send('User deleted');
}));
}
});
}));
}));
}));
});
//获取单个用户
app.get('/admin/get-user/:id', (req, res) => {
const { id } = req.params;
const query = 'SELECT * FROM users WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error getting user:', err);
res.status(500).json({ error: 'Failed to get user' });
} else if (results.length === 0) {
res.status(404).json({ error: 'User not found' });
} else {
res.json(results[0]);
}
});
});
// 编辑借阅记录(注意:通常借阅记录不需要编辑,但这里为了完整性提供示例)
app.post('/admin/edit-borrow-record', (req, res) => {
const { id, user_id, book_id, borrow_date } = req.body;
const query = 'UPDATE borrow_records SET user_id = ?, book_id = ?, borrow_date = ? WHERE id = ?';
db.query(query, [user_id, book_id, borrow_date, id], (err, results) => {
if (err) {
console.error('Error editing borrow record:', err);
res.status(500).json({ error: 'Failed to edit borrow record' });
} else {
res.status(200).send('Borrow record edited successfully');
}
});
});
// 删除借阅记录
app.post('/admin/delete-borrow-record', (req, res) => {
const { id } = req.body;
code Copy code
if (!id || isNaN(id)) {
return res.status(400).send('无效的借阅记录ID格式');
}
const query = 'DELETE FROM borrow_records WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error deleting borrow record:', err);
return res.status(500).send('服务器错误');
}
if (results.affectedRows > 0) {
res.send('借阅记录删除成功');
} else {
res.status(404).send('没有找到该借阅记录');
}
});
});
// 获取单个借阅记录详情的路由
app.get('/admin/get-borrow-record/:id', (req, res) => {
const { id } = req.params;
// 验证id是否为有效的数字且大于0
if (!Number.isInteger(Number(id)) || Number(id) <= 0) {
res.status(400).json({ error: 'Invalid borrow record ID format or value' });
return;
}
const query = SELECT * FROM borrow_records WHERE id =? ;
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error getting borrow record:', err);
res.status(500).json({ error: 'Failed to get borrow record. Error details: ' + err.message });
} else if (results.length === 0) {
res.status(404).json({ error: 'Borrow record not found' });
} else {
res.json(results[0]);
}
});
});
// 添加收藏路由
app.post('/user/add-favorite', (req, res) => {
const { userId, bookId } = req.body;
// 先检查该用户是否已经收藏了这本书
const checkFavoriteQuery = 'SELECT * FROM favorites WHERE user_id =? AND book_id =?';
db.query(checkFavoriteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
// 已收藏,提示用户
res.status(400).json({ error: 'This book has already been added to favorites' });
} else {
// 可以添加收藏,插入记录到 favorites 表
const insertFavoriteQuery = 'INSERT INTO favorites (user_id, book_id) VALUES (?,?)';
db.query(insertFavoriteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Failed to add to favorites' });
} else {
// 返回成功的 JSON 响应
res.status(200).json({ message: 'Book added to favorites successfully' });
}
});
}
});
});
// 删除收藏书籍路由
app.post('/user/delete-favorite', (req, res) => {
const { userId, bookId } = req.body;
const deleteQuery = 'DELETE FROM favorites WHERE user_id =? AND book_id =?';
db.query(deleteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error when deleting favorite' });
} else if (results.affectedRows === 0) {
// 如果受影响的行数为0,表示没有找到对应的收藏记录,即可能已经不存在该收藏了
res.status(400).json({ error: 'This book is not in your favorites' });
} else {
res.status(200).json({ message: 'Book removed from favorites successfully' });
}
});
});
// 从收藏中借阅书籍
app.post('/user/borrow-from-favorite', (req, res) => {
const { userId, bookId } = req.body;
// 先从收藏中删除这本书
const deleteFavoriteQuery = 'DELETE FROM favorites WHERE user_id = ? AND book_id = ?';
db.query(deleteFavoriteQuery, [userId, bookId], (err, deleteResults) => {
if (err) {
console.error('Error deleting favorite before borrowing:', err);
res.status(500).json({ error: 'Failed to borrow book from favorites' });
return;
}
if (deleteResults.affectedRows === 0) {
res.status(400).json({ error: 'This book is not in your favorites' });
return;
}
code Copy code
// 然后借阅这本书
const borrowQuery = 'INSERT INTO borrow_records (user_id, book_id, borrow_date) VALUES (?, ?, NOW())';
db.query(borrowQuery, [userId, bookId], (err, borrowResults) => {
if (err) {
console.error('Error borrowing book:', err);
res.status(500).json({ error: 'Failed to borrow book' });
} else {
// 返回成功的 JSON 响应
res.status(200).json({ message: 'Book borrowed from favorites successfully' });
}
});
});
// 监听端口
const PORT = 3000;
app.listen(PORT, () => {
console.log(Server running on port ${PORT});
});修改代码,让删除图书的id改成用图书进行删除
2. 修改后端代码 确保后端的删除图书逻辑也能够通过书名删除。在 delete-book 的路由中,修改 SQL 查询来删除匹配书名的记录:
javascript Copy code
// 删除图书
app.post('/admin/delete-book', (req, res) => {
const { title } = req.body; // 使用书名进行删除
// 确保书名是有效的字符串
if (!title || typeof title !== 'string') {
return res.status(400).json({ error: 'Invalid book title format' });
}
// SQL查询使用书名删除图书
const query = 'DELETE FROM books WHERE title = ?';
db.query(query, [title], (err, results) => {
if (err) {
console.error('Error deleting book:', err);
return res.status(500).json({ error: 'Failed to delete book. Error details: ' + err.message });
} else {
// 检查是否有行被删除
if (results.affectedRows > 0) {
res.send('Book deleted');
} else {
res.status(404).send('No book found with that title');
}
}
});
});
3. 完整示例:修改后的前端和后端
在删除图书的表单中添加输入框获取书名。
更新删除逻辑以依据书名删除。
最后 完成上述代码更改后,你应该可以通过输入书名来删除图书,而不需要使用 ID。请在代码中添加必要的错误处理、权限检查和其他逻辑,以确保生产环境的安全和稳定。进行全面的测试以确保所有功能都能正常工作。
// 根据type动态创建表单
switch (type) {
case 'add':
formContainer.innerHTML = `
<input type="text" placeholder="书名">
<input type="text" placeholder="作者">
<input type="number" placeholder="出版年份">
<button onclick="addBook()">添加</button>
`;
break;
case 'delete':
formContainer.innerHTML = `
<h2>删除图书</h2>
<input type="text" id="bookTitle" placeholder="输入书名" style="width: 200px;" />
<button onclick="deleteBook()">删除</button>
`;
break;
case 'borrowRecords':
formContainer.innerHTML = `<h2>借阅记录</h2><div id="borrowRecordsList"></div>`;
loadBorrowRecords();
break;
case 'edit':
formContainer.innerHTML = `
<h2>修改图书</h2>
<input type="text" placeholder="旧书名" id="oldTitle">
<input type="text" placeholder="新书名" id="newTitle">
<input type="text" placeholder="新作者" id="newAuthor">
<input type="number" placeholder="新出版年份" id="newYearPublished">
<button onclick="editBook()">修改</button>
`;
break;
case 'search':
formContainer.innerHTML = `
<input type="text" placeholder="搜索关键词" id="searchKeyword">
<button onclick="searchBooks()">查询</button>
`;
break;
case 'userManagement':
loadUsers().then(users => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">用户管理</h2>
<div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
<ul style="list-style-type: none; padding: 0;">
`;
users.forEach(user => {
formContainer.innerHTML += `
<li style="margin: 10px 0;">
${user.username}
<button onclick="editUserForm('${user.id}')">编辑</button>
<button onclick="deleteUser('${user.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
});
break;
case 'dataManagement':
formContainer.innerHTML = `
<h2>数据管理</h2>
<!-- 这里可以添加数据管理的相关表单或内容 -->
`;
loadBooks(); // 正确的位置
break;
case 'borrowRecords':
formContainer.innerHTML = `
<h2>借阅记录</h2>
<!-- 这里可以添加借阅记录的相关表单或内容 -->
`;
break;
case 'editUser':
fetch(`http://localhost:3000/admin/get-user/${id}`)
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch user data');
}
return response.json();
})
.then(user => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<input type="hidden" value="${id}" name="id">
<input type="text" placeholder="用户名" value="${user.username}" name="username">
<input type="password" placeholder="密码" name="password">
<select name="role">
<option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
<option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
</select>
<button onclick="editUser(${id})">保存</button>
`;
})
.catch(error => {
console.error('Error fetching user data:', error);
alert('Failed to fetch user data: ' + error.message);
});
break;
case 'deleteUser':
if (confirm(`确定要删除用户ID为${id}的用户吗?此操作不可撤销!`)) {
deleteUser(id);
}
break;
default:
formContainer.style.display = 'none';
}
}
function addBook() {
// 获取表单数据
const formContainer = document.getElementById('formContainer');
const title = formContainer.querySelector('input[placeholder="书名"]').value;
const author = formContainer.querySelector('input[placeholder="作者"]').value;
const year_published = formContainer.querySelector('input[placeholder="出版年份"]').value; // 使用正确的变量名
// 发送增加图书的请求
fetch('http://localhost:3000/admin/add-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin' // 假设已经在某处设置了用户类型
},
body: JSON.stringify({ title, author, year_published }) // 使用正确的变量名
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Book added:', data);
alert('图书添加成功:' + data); // 显示成功消息
// 可选:清空表单
formContainer.innerHTML = '';
formContainer.style.display = 'none';
// 可选:更新图书列表(如果有的话)
})
.catch(error => {
console.error('Error adding book:', error);
alert('添加图书时出错:' + error.message);
});
}
function searchBooks() {
const searchKeyword = document.getElementById('searchKeyword').value;
fetch('http://localhost:3000/user/search-books', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ keyword: searchKeyword })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
displaySearchResults(data);
})
.catch(error => {
console.error('Error searching books:', error);
alert('搜索图书时出错:' + error.message);
});
}
function displaySearchResults(books) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<div>
<button onclick="showForm('search')">返回继续搜索</button>
</div>
<h2>搜索结果</h2>
`;
if (books.length === 0) {
formContainer.innerHTML += '<p>未找到图书。</p>';
} else {
const resultsList = document.createElement('ul');
books.forEach(book => {
const listItem = document.createElement('li');
listItem.textContent = `${book.title} by ${book.author} (${book.year_published})`;
resultsList.appendChild(listItem);
});
formContainer.appendChild(resultsList);
}
}
function loadBooks() {
console.log('Starting to load books...');
return fetch('http://localhost:3000/admin/get-books')
.then(response => {
console.log('Received response from get-books:', response);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(books => {
console.log('Loaded books data:', books);
displayBooks(books);
return Promise.resolve(); // 显式返回一个已解决的Promise,确保外层能正确链式调用
})
.catch(error => {
console.error('Error loading books:', error);
alert('加载图书时出错:' + error.message);
return Promise.reject(error); // 出现错误时返回一个被拒绝的Promise,传播错误
});
}
function displayBooks(books) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">图书管理</h2>
<div class="book-list-container">
<ul>
`;
books.forEach(book => {
formContainer.innerHTML += `
<li>
${book.title} by ${book.author} (${book.year_published})
<button onclick="editBookForm('${book.id}')">编辑</button>
<button onclick="deleteBookConfirm('${book.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
return Promise.resolve();
code Copy code
function loadUsers() {
return fetch('http://localhost:3000/admin/get-users')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(users => {
displayUsers(users);
return users; // 将处理后的用户数据返回,使得外层能接收到这个 Promise 结果
})
.catch(error => {
console.error('Error loading users:', error);
alert('加载用户时出错:' + error.message);
throw error; // 可以选择重新抛出错误,让调用处能进一步处理
});
}
function displayUsers(users) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">用户管理</h2>
<div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
<ul style="list-style-type: none; padding: 0;">
`;
users.forEach(user => {
formContainer.innerHTML += `
<li style="margin: 10px 0;">
${user.username}
<button onclick="editUserForm('${user.id}')">编辑</button>
<button onclick="deleteUserConfirm('${user.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
}
function loadBorrowRecords() {
fetch('http://localhost:3000/admin/borrow-records') // 确保此 API 地址是正确的
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(records => {
console.log('Loaded borrow records:', records); // 检查返回的 records
displayBorrowRecords(records);
})
.catch(error => {
console.error('Error loading borrow records:', error);
alert('加载借阅记录时出错:' + error.message);
});
function displayBorrowRecords(records) {
console.log('Borrow records:', records); // Debug log - 确保调用时返回记录的结构
code Copy code
const borrowRecordsList = document.getElementById('borrowRecordsList');
borrowRecordsList.innerHTML = ''; // 清空之前的内容
if (records.length === 0) {
borrowRecordsList.innerHTML = '<p>无借阅记录。</p>';
} else {
const table = document.createElement('table');
table.innerHTML = `
<tr>
<th>用户名</th>
<th>书名</th>
<th>作者</th>
<th>借阅日期</th>
<th>操作</th>
</tr>
`;
records.forEach(record => {
console.log('Record:', record); // 输出每一条记录
const row = document.createElement('tr');
row.innerHTML = `
<td>${record.username}</td>
<td>${record.title}</td>
<td>${record.author}</td>
<td>${record.borrow_date}</td>
<td>
<button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
</td>
`;
table.appendChild(row);
});
borrowRecordsList.appendChild(table);
}
code Copy code
function deleteUser(id) {
fetch(`http://localhost:3000/admin/delete-user`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok: ' + response.statusText);
}
return response.text();
})
.then(data => {
alert(data);
loadUsers(); // 刷新用户列表
})
.catch(error => {
console.error('Error deleting user:', error);
alert('删除用户时出现错误:' + error.message);
});
}
function editUserForm(id) {
fetch(`http://localhost:3000/admin/get-user/${id}`)
.then(response => {
if (!response.ok) {
throw new Error('获取用户信息失败,状态码:' + response.status);
}
return response.json();
})
.then(user => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<form id="editUserForm">
<input type="hidden" value="${id}" name="id">
<input type="text" placeholder="用户名" value="${user.username}" name="username">
<input type="password" placeholder="密码" name="password">
<select name="role">
<option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
<option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
</select>
<button type="button" onclick="editUser(${id})">保存</button>
</form>
`;
})
.catch(error => {
console.error('编辑用户信息获取出错:', error);
alert('获取用户信息失败,请稍后重试:' + error.message);
});
}
function editUser(id) {
const form = document.querySelector(`#editUserForm`);
if (!form || !(form instanceof HTMLFormElement)) {
console.error('Invalid form element');
return;
}
const formData = new FormData(form);
const data = Object.fromEntries(formData.entries());
// Simple validation for required fields
if (!data.username || !data.password || !data.role) {
alert('请填写所有必填字段');
return;
}
fetch(`http://localhost:3000/admin/edit-user`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
.then(response => response.text())
.then(data => {
alert(data);
loadUsers(); // 刷新用户列表
})
.catch(error => {
console.error('Error editing user:', error);
alert('编辑用户信息时出现错误,请稍后重试:' + error.message);
});
}
function editBookForm(bookId) {
// 先调用获取所有图书的后端路由以获取图书数据
fetch('http://localhost:3000/admin/get-books')
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch all books data');
}
return response.json();
})
.then(allBooks => {
// 在获取到的所有图书数据中查找对应id的图书
const targetBook = allBooks.find(book => book.id === Number(bookId));
if (!targetBook) {
alert('未找到对应图书信息,请确认图书ID是否正确');
return;
}
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2>修改图书</h2>
<input type="text" placeholder="旧书名" id="oldTitle" value="${targetBook.title}" disabled>
<input type="text" placeholder="新书名" id="newTitle">
<input type="text" placeholder="新作者" id="newAuthor">
<input type="number" placeholder="新出版年份" id="newYearPublished">
<button onclick="editBook()">保存</button>
`;
})
.catch(error => {
console.error('Error fetching book data:', error);
alert('获取图书信息失败,请稍后重试:' + error.message);
});
code Copy code
function deleteBookConfirm(bookId) {
if (!bookId) {
alert('无效的图书ID');
return;
}
if (confirm(`确定要删除图书ID为${bookId}的图书吗?此操作不可撤销!`)) {
deleteBook(bookId);
}
function deleteBook() {
// 获取书名
const formContainer = document.getElementById('formContainer');
const bookTitle = formContainer.querySelector('#bookTitle').value; // 假设我们的输入框 ID 为 bookTitle
code Copy code
if (!bookTitle) {
alert('请输入书名以进行删除');
return;
}
fetch('http://localhost:3000/admin/delete-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ title: bookTitle }) // 发送书名
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Book deleted:', data);
alert('图书删除成功');
loadBooks(); // 重新加载图书列表
})
.catch(error => {
console.error('Error deleting book:', error);
alert('删除图书时出错:' + error.message);
});
function editBook() {
const newTitle = document.getElementById('newTitle').value.trim();
const newAuthor = document.getElementById('newAuthor').value.trim();
const newYearPublished = document.getElementById('newYearPublished').value.trim();
code Copy code
// 简单验证输入框是否为空
if (!newTitle || !newAuthor || !newYearPublished) {
alert('请填写所有修改信息');
return;
}
const oldTitle = document.getElementById('oldTitle').value; // 注意,没有trim(),因为oldTitle是禁用输入,不应更改
fetch('http://localhost:3000/admin/edit-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ oldTitle, newTitle, newAuthor, newYearPublished })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok: ' + response.statusText);
}
return response.text();
})
.then(data => {
console.log('Book edited:', data);
alert('图书修改成功');
showForm('dataManagement'); // 返回数据管理界面
})
.catch(error => {
console.error('Error editing book:', error);
alert('修改图书时出错:' + error.message);
});
}
function deleteBorrowRecordConfirm(recordId) {
console.log('Attempting to delete record with ID:', recordId);
if (!recordId) {
alert('无效的借阅记录ID');
return;
}
if (confirm(确定要删除借阅记录ID为${recordId}的记录吗?此操作不可撤销!)) {
deleteBorrowRecord(recordId);
}
}
function deleteBorrowRecord(recordId) {
fetch('http://localhost:3000/admin/delete-borrow-record ', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ id: recordId }) // 发送要删除记录的 ID
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Borrow record deleted:', data);
alert('借阅记录删除成功');
loadBorrowRecords(); // 重新加载借阅记录列表
})
.catch(error => {
console.error('Error deleting borrow record:', error);
alert('删除借阅记录时出错:' + error.message);
});
}
const app = express();
app.use(cors());
app.use(bodyParser.json());
// MySQL数据库连接配置
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456', // 替换为你的MySQL密码
database: 'librarysystem'
});
db.connect(err => {
if (err) {
throw err;
}
console.log('MySQL connected...');
});
// 登录路由
app.post('/login', (req, res) => {
const { username, password } = req.body;
const query = 'SELECT * FROM users WHERE username = ? AND password = ?';
db.query(query, [username, password], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
console.log("Login successful, sending response:", results[0]);
res.json(results[0]);
} else {
res.status(400).json({ error: 'Invalid login' });
}
});
});
// 注册路由
app.post('/register', (req, res) => {
const { username, password } = req.body;
// 检查用户名是否已存在
const checkUserQuery = 'SELECT * FROM users WHERE username = ?';
db.query(checkUserQuery, [username], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
// 用户名已存在
res.status(400).json({ error: 'Username already exists' });
} else {
// 用户名不存在,可以注册
const insertUserQuery = 'INSERT INTO users (username, password, role) VALUES (?, ?, ?)';
db.query(insertUserQuery, [username, password, 'user'], (err, results) => {
if (err) {
res.status(500).json({ error: 'Failed to register user' });
} else {
res.status(201).send('User registered successfully');
}
});
}
});
});
// 管理员操作路由
// 添加图书
app.post('/admin/add-book', (req, res) => {
const { title, author, year_published } = req.body;
const query = 'INSERT INTO books (title, author, year_published) VALUES (?, ?, ?)';
db.query(query, [title, author, year_published], (err, results) => {
if (err) {
console.error('Error adding book:', err);
res.status(500).json({ error: 'Failed to add book' });
} else {
res.status(200).send('Book added successfully');
}
});
});
// 删除图书
app.post('/admin/delete-book', (req, res) => {
const { id } = req.body;
code Copy code
// 确保 ID 是有效的数字
if (!id || isNaN(id)) {
res.status(400).json({ error: 'Invalid book ID format' });
return;
}
const query = 'DELETE FROM books WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error deleting book:', err);
res.status(500).json({ error: 'Failed to delete book. Error details: ' + err.message });
} else {
// 检查是否有行被删除
if (results.affectedRows > 0) {
res.send('Book deleted');
} else {
res.status(404).send('No book found with this ID');
}
}
});
// 用户操作路由
// 搜索书籍
app.post('/user/search-books', (req, res) => {
const { keyword } = req.body;
const query = SELECT * FROM books WHERE id = ? OR title LIKE ? OR author LIKE ? ;
db.query(query, [keyword, %${keyword}%, %${keyword}%], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 添加收藏
// 获取用户的收藏书籍
app.get('/user/favorites/:userId', (req, res) => {
const { userId } = req.params;
const query = SELECT b.id, b.title, b.author FROM favorites f JOIN books b ON f.book_id = b.id WHERE f.user_id = ? ;
db.query(query, [userId], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 编辑图书
app.post('/admin/edit-book', (req, res) => {
const { oldTitle, newTitle, newAuthor, newYearPublished } = req.body;
code Copy code
// 验证每个字段
if (!oldTitle || !newTitle || !newAuthor || !newYearPublished) {
return res.status(400).json({ error: '所有字段都需要填写' });
}
const query = 'UPDATE books SET title=?, author=?, year_published=? WHERE title=?';
db.query(query, [newTitle, newAuthor, newYearPublished, oldTitle], (err, results) => {
if (err) {
console.error('Error editing book:', err);
return res.status(500).json({ error: 'Failed to edit book. Error details: ' + err.message });
}
// 检查是否有行被更新
if (results.affectedRows > 0) {
res.status(200).send('Book edited successfully');
} else {
res.status(404).send('No book found with that title for editing');
}
});
});
app.post('/admin/edit-book', (req, res) => {
const { oldTitle, newTitle, newAuthor, newYearPublished } = req.body;
code Copy code
// 验证每个字段
if (!oldTitle || !newTitle || !newAuthor || !newYearPublished) {
return res.status(400).json({ error: '所有字段都需要填写' });
}
const query = 'UPDATE books SET title=?, author=?, year_published=? WHERE title=?';
db.query(query, [newTitle, newAuthor, newYearPublished, oldTitle], (err, results) => {
if (err) {
console.error('Error editing book:', err);
return res.status(500).json({ error: 'Failed to edit book. Error details: ' + err.message });
}
// 检查是否有行被更新
if (results.affectedRows > 0) {
res.status(200).send('Book edited successfully');
} else {
res.status(404).send('No book found with that title for editing');
}
});
app.get('/admin/get-books', (req, res) => {
const query = 'SELECT * FROM books';
db.query(query, (err, results) => {
if (err) {
console.error('Error getting books:', err);
res.status(500).json({ error: 'Failed to get books' });
} else {
res.json(results);
}
});
});
// 获取所有用户
app.get('/admin/get-users', (req, res) => {
const query = 'SELECT * FROM users';
db.query(query, (err, results) => {
if (err) {
console.error('Error getting users:', err);
res.status(500).json({ error: 'Failed to get users' });
} else {
res.json(results);
}
});
});
// 借阅书籍
app.post('/user/borrow-book', (req, res) => {
const { userId, bookId } = req.body;
const query = 'INSERT INTO borrow_records (user_id, book_id, borrow_date) VALUES (?, ?, NOW())';
db.query(query, [userId, bookId], (err, results) => {
if (err) {
console.error('Error borrowing book:', err);
res.status(500).json({ error: 'Failed to borrow book' });
} else {
res.status(200).send('Book borrowed successfully');
}
});
});
// 获取借阅历史
app.get('/user/borrow-history/:userId', (req, res) => {
const { userId } = req.params;
const query = SELECT b.title, b.author, br.borrow_date FROM borrow_records br JOIN books b ON br.book_id = b.id WHERE br.user_id = ? ORDER BY br.borrow_date DESC ;
db.query(query, [userId], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 获取所有借阅记录(管理员用)
// 获取所有借阅记录(管理员用)
app.get('/admin/borrow-records', (req, res) => {
const query = SELECT br.id, u.username, b.title, b.author, br.borrow_date FROM borrow_records br JOIN users u ON br.user_id = u.id JOIN books b ON br.book_id = b.id ORDER BY br.borrow_date DESC ;
db.query(query, (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
// Ensure that the ID is included in results
res.json(results);
}
});
});
// 编辑用户
app.post('/admin/edit-user', (req, res) => {
const { id, username, password, role } = req.body;
const query = 'UPDATE users SET username =?, password =?, role =? WHERE id =?';
db.query(query, [username, password, role, id], (err, results) => {
if (err) {
console.error('编辑用户信息出错,编辑的用户ID:', id);
console.error('错误信息:', err.message);
console.error('错误堆栈:', err.stack);
res.status(500).json({ error: 'Failed to edit user' });
} else {
console.log('用户信息编辑成功,编辑的用户ID:', id);
res.status(200).send('User edited successfully');
}
});
});
// 删除用户
app.post('/admin/delete-user', (req, res) => {
const { id } = req.body;
db.beginTransaction((err => {
if (err) {
console.error('Error starting transaction:', err);
res.status(500).send('Server error starting transaction');
return;
}
// 先删除 borrow_records 表中与该用户相关的记录
const deleteBorrowRecordsQuery = 'DELETE FROM borrow_records WHERE user_id =?';
db.query(deleteBorrowRecordsQuery, [id], (err => {
if (err) {
db.rollback(() => {
console.error('Error deleting related borrow records, rolling back transaction:', err);
res.status(500).send('Server error when deleting related borrow records, transaction rolled back');
});
return;
}
// 再删除 favorites 表中与该用户相关的记录
const deleteFavoritesQuery = 'DELETE FROM favorites WHERE user_id =?';
db.query(deleteFavoritesQuery, [id], (err => {
if (err) {
db.rollback(() => {
console.error('Error deleting related favorites, rolling back transaction:', err);
res.status(500).send('Server error when deleting related favorites, transaction rolled back');
});
return;
}
// 最后执行删除用户操作
const query = 'DELETE FROM users WHERE id =?';
db.query(query, [id], (err, results) => {
if (err) {
db.rollback(() => {
console.error('删除用户出错,要删除的用户ID:', id);
console.error('错误信息:', err.message);
console.error('错误堆栈:', err.stack);
res.status(500).send('Server error, transaction rolled back');
});
} else {
db.commit((err => {
if (err) {
console.error('Error committing transaction:', err);
res.status(500).send('Server error committing transaction');
return;
}
console.log('用户删除成功,删除的用户ID:', id);
res.send('User deleted');
}));
}
});
}));
}));
}));
});
//获取单个用户
app.get('/admin/get-user/:id', (req, res) => {
const { id } = req.params;
const query = 'SELECT * FROM users WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error getting user:', err);
res.status(500).json({ error: 'Failed to get user' });
} else if (results.length === 0) {
res.status(404).json({ error: 'User not found' });
} else {
res.json(results[0]);
}
});
});
// 编辑借阅记录(注意:通常借阅记录不需要编辑,但这里为了完整性提供示例)
app.post('/admin/edit-borrow-record', (req, res) => {
const { id, user_id, book_id, borrow_date } = req.body;
const query = 'UPDATE borrow_records SET user_id = ?, book_id = ?, borrow_date = ? WHERE id = ?';
db.query(query, [user_id, book_id, borrow_date, id], (err, results) => {
if (err) {
console.error('Error editing borrow record:', err);
res.status(500).json({ error: 'Failed to edit borrow record' });
} else {
res.status(200).send('Borrow record edited successfully');
}
});
});
// 删除借阅记录
app.post('/admin/delete-borrow-record', (req, res) => {
const { id } = req.body;
code Copy code
if (!id || isNaN(id)) {
return res.status(400).send('无效的借阅记录ID格式');
}
const query = 'DELETE FROM borrow_records WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error deleting borrow record:', err);
return res.status(500).send('服务器错误');
}
if (results.affectedRows > 0) {
res.send('借阅记录删除成功');
} else {
res.status(404).send('没有找到该借阅记录');
}
});
});
// 获取单个借阅记录详情的路由
app.get('/admin/get-borrow-record/:id', (req, res) => {
const { id } = req.params;
// 验证id是否为有效的数字且大于0
if (!Number.isInteger(Number(id)) || Number(id) <= 0) {
res.status(400).json({ error: 'Invalid borrow record ID format or value' });
return;
}
const query = SELECT * FROM borrow_records WHERE id =? ;
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error getting borrow record:', err);
res.status(500).json({ error: 'Failed to get borrow record. Error details: ' + err.message });
} else if (results.length === 0) {
res.status(404).json({ error: 'Borrow record not found' });
} else {
res.json(results[0]);
}
});
});
// 添加收藏路由
app.post('/user/add-favorite', (req, res) => {
const { userId, bookId } = req.body;
// 先检查该用户是否已经收藏了这本书
const checkFavoriteQuery = 'SELECT * FROM favorites WHERE user_id =? AND book_id =?';
db.query(checkFavoriteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
// 已收藏,提示用户
res.status(400).json({ error: 'This book has already been added to favorites' });
} else {
// 可以添加收藏,插入记录到 favorites 表
const insertFavoriteQuery = 'INSERT INTO favorites (user_id, book_id) VALUES (?,?)';
db.query(insertFavoriteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Failed to add to favorites' });
} else {
// 返回成功的 JSON 响应
res.status(200).json({ message: 'Book added to favorites successfully' });
}
});
}
});
});
// 删除收藏书籍路由
app.post('/user/delete-favorite', (req, res) => {
const { userId, bookId } = req.body;
const deleteQuery = 'DELETE FROM favorites WHERE user_id =? AND book_id =?';
db.query(deleteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error when deleting favorite' });
} else if (results.affectedRows === 0) {
// 如果受影响的行数为0,表示没有找到对应的收藏记录,即可能已经不存在该收藏了
res.status(400).json({ error: 'This book is not in your favorites' });
} else {
res.status(200).json({ message: 'Book removed from favorites successfully' });
}
});
});
// 从收藏中借阅书籍
app.post('/user/borrow-from-favorite', (req, res) => {
const { userId, bookId } = req.body;
// 先从收藏中删除这本书
const deleteFavoriteQuery = 'DELETE FROM favorites WHERE user_id = ? AND book_id = ?';
db.query(deleteFavoriteQuery, [userId, bookId], (err, deleteResults) => {
if (err) {
console.error('Error deleting favorite before borrowing:', err);
res.status(500).json({ error: 'Failed to borrow book from favorites' });
return;
}
if (deleteResults.affectedRows === 0) {
res.status(400).json({ error: 'This book is not in your favorites' });
return;
}
code Copy code
// 然后借阅这本书
const borrowQuery = 'INSERT INTO borrow_records (user_id, book_id, borrow_date) VALUES (?, ?, NOW())';
db.query(borrowQuery, [userId, bookId], (err, borrowResults) => {
if (err) {
console.error('Error borrowing book:', err);
res.status(500).json({ error: 'Failed to borrow book' });
} else {
// 返回成功的 JSON 响应
res.status(200).json({ message: 'Book borrowed from favorites successfully' });
}
});
});
// 监听端口
const PORT = 3000;
app.listen(PORT, () => {
console.log(Server running on port ${PORT});
});修改代码,让删除图书模块的id改成用图书进行删除,因为还有图书管理删除模块,在原有代码与他区分开来
2. 后端代码修改 在后端代码中,添加一个新的路由处理请求,通过书名删除图书。将 delete-book 路由修改为 delete-book-by-title。
javascript Copy code
// 删除图书通过书名
app.post('/admin/delete-book-by-title', (req, res) => {
const { title } = req.body; // 获取书名
// 确保书名是有效的字符串
if (!title || typeof title !== 'string') {
return res.status(400).json({ error: 'Invalid book title format' });
}
// SQL 查询使用书名删除图书
const query = 'DELETE FROM books WHERE title = ?';
db.query(query, [title], (err, results) => {
if (err) {
console.error('Error deleting book:', err);
return res.status(500).json({ error: 'Failed to delete book. Error details: ' + err.message });
} else {
if (results.affectedRows > 0) {
res.send('Book deleted');
} else {
res.status(404).send('No book found with that title');
}
}
});
});
3. 测试
启动你的 Node.js 服务器,并确保没有错误。
确保在数据库中有一些图书记录作为测试。
在管理员页面中输入书名进行删除操作,观察删除是否成功,并查看控制台是否输出相关信息。
通过这种方式,您可以保持原有的 ID 删除功能,并且新增书名删除功能,清晰地分开了两者的工作逻辑。
// 根据type动态创建表单
switch (type) {
case 'add':
formContainer.innerHTML = `
<input type="text" placeholder="书名">
<input type="text" placeholder="作者">
<input type="number" placeholder="出版年份">
<button onclick="addBook()">添加</button>
`;
break;
case 'delete':
formContainer.innerHTML = `
<h2>删除图书</h2>
<input type="text" id="bookTitle" placeholder="输入书名" style="width: 200px;" />
<button onclick="deleteBook()">删除</button>
`;
break;
case 'borrowRecords':
formContainer.innerHTML = `<h2>借阅记录</h2><div id="borrowRecordsList"></div>`;
loadBorrowRecords();
break;
case 'edit':
formContainer.innerHTML = `
<h2>修改图书</h2>
<input type="text" placeholder="旧书名" id="oldTitle">
<input type="text" placeholder="新书名" id="newTitle">
<input type="text" placeholder="新作者" id="newAuthor">
<input type="number" placeholder="新出版年份" id="newYearPublished">
<button onclick="editBook()">修改</button>
`;
break;
case 'search':
formContainer.innerHTML = `
<input type="text" placeholder="搜索关键词" id="searchKeyword">
<button onclick="searchBooks()">查询</button>
`;
break;
case 'userManagement':
loadUsers().then(users => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">用户管理</h2>
<div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
<ul style="list-style-type: none; padding: 0;">
`;
users.forEach(user => {
formContainer.innerHTML += `
<li style="margin: 10px 0;">
${user.username}
<button onclick="editUserForm('${user.id}')">编辑</button>
<button onclick="deleteUser('${user.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
});
break;
case 'dataManagement':
formContainer.innerHTML = `
<h2>数据管理</h2>
<!-- 这里可以添加数据管理的相关表单或内容 -->
`;
loadBooks(); // 正确的位置
break;
case 'borrowRecords':
formContainer.innerHTML = `
<h2>借阅记录</h2>
<!-- 这里可以添加借阅记录的相关表单或内容 -->
`;
break;
case 'editUser':
fetch(`http://localhost:3000/admin/get-user/${id}`)
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch user data');
}
return response.json();
})
.then(user => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<input type="hidden" value="${id}" name="id">
<input type="text" placeholder="用户名" value="${user.username}" name="username">
<input type="password" placeholder="密码" name="password">
<select name="role">
<option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
<option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
</select>
<button onclick="editUser(${id})">保存</button>
`;
})
.catch(error => {
console.error('Error fetching user data:', error);
alert('Failed to fetch user data: ' + error.message);
});
break;
case 'deleteUser':
if (confirm(`确定要删除用户ID为${id}的用户吗?此操作不可撤销!`)) {
deleteUser(id);
}
break;
case 'deleteByTitle':
formContainer.innerHTML = `
<h2>删除图书</h2>
<input type="text" id="bookTitle" placeholder="输入书名" style="width: 200px;" />
<button onclick="deleteBookByTitle()">删除</button>
`;
break;
default:
formContainer.style.display = 'none';
}
}
//删除图书
function deleteBookByTitle() {
const bookTitle = document.getElementById('bookTitle').value; // 获取书名
if (!bookTitle) {
alert('请输入书名以进行删除');
return;
}
fetch('http://localhost:3000/admin/delete-book-by-title', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ title: bookTitle }) // 传递书名
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Book deleted:', data);
alert('图书删除成功');
loadBooks(); // 重新加载图书列表
})
.catch(error => {
console.error('Error deleting book:', error);
alert('删除图书时出错:' + error.message);
});
}
function addBook() {
// 获取表单数据
const formContainer = document.getElementById('formContainer');
const title = formContainer.querySelector('input[placeholder="书名"]').value;
const author = formContainer.querySelector('input[placeholder="作者"]').value;
const year_published = formContainer.querySelector('input[placeholder="出版年份"]').value; // 使用正确的变量名
code Copy code
// 发送增加图书的请求
fetch('http://localhost:3000/admin/add-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin' // 假设已经在某处设置了用户类型
},
body: JSON.stringify({ title, author, year_published }) // 使用正确的变量名
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Book added:', data);
alert('图书添加成功:' + data); // 显示成功消息
// 可选:清空表单
formContainer.innerHTML = '';
formContainer.style.display = 'none';
// 可选:更新图书列表(如果有的话)
})
.catch(error => {
console.error('Error adding book:', error);
alert('添加图书时出错:' + error.message);
});
}
function searchBooks() {
const searchKeyword = document.getElementById('searchKeyword').value;
fetch('http://localhost:3000/user/search-books', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ keyword: searchKeyword })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
displaySearchResults(data);
})
.catch(error => {
console.error('Error searching books:', error);
alert('搜索图书时出错:' + error.message);
});
}
function displaySearchResults(books) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<div>
<button onclick="showForm('search')">返回继续搜索</button>
</div>
<h2>搜索结果</h2>
`;
if (books.length === 0) {
formContainer.innerHTML += '<p>未找到图书。</p>';
} else {
const resultsList = document.createElement('ul');
books.forEach(book => {
const listItem = document.createElement('li');
listItem.textContent = `${book.title} by ${book.author} (${book.year_published})`;
resultsList.appendChild(listItem);
});
formContainer.appendChild(resultsList);
}
}
function loadBooks() {
console.log('Starting to load books...');
return fetch('http://localhost:3000/admin/get-books')
.then(response => {
console.log('Received response from get-books:', response);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(books => {
console.log('Loaded books data:', books);
displayBooks(books);
return Promise.resolve(); // 显式返回一个已解决的Promise,确保外层能正确链式调用
})
.catch(error => {
console.error('Error loading books:', error);
alert('加载图书时出错:' + error.message);
return Promise.reject(error); // 出现错误时返回一个被拒绝的Promise,传播错误
});
}
function displayBooks(books) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">图书管理</h2>
<div class="book-list-container">
<ul>
`;
books.forEach(book => {
formContainer.innerHTML += `
<li>
${book.title} by ${book.author} (${book.year_published})
<button onclick="editBookForm('${book.id}')">编辑</button>
<button onclick="deleteBookConfirm('${book.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
return Promise.resolve();
code Copy code
function loadUsers() {
return fetch('http://localhost:3000/admin/get-users')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(users => {
displayUsers(users);
return users; // 将处理后的用户数据返回,使得外层能接收到这个 Promise 结果
})
.catch(error => {
console.error('Error loading users:', error);
alert('加载用户时出错:' + error.message);
throw error; // 可以选择重新抛出错误,让调用处能进一步处理
});
}
function displayUsers(users) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">用户管理</h2>
<div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
<ul style="list-style-type: none; padding: 0;">
`;
users.forEach(user => {
formContainer.innerHTML += `
<li style="margin: 10px 0;">
${user.username}
<button onclick="editUserForm('${user.id}')">编辑</button>
<button onclick="deleteUserConfirm('${user.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
}
function loadBorrowRecords() {
fetch('http://localhost:3000/admin/borrow-records') // 确保此 API 地址是正确的
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(records => {
console.log('Loaded borrow records:', records); // 检查返回的 records
displayBorrowRecords(records);
})
.catch(error => {
console.error('Error loading borrow records:', error);
alert('加载借阅记录时出错:' + error.message);
});
function displayBorrowRecords(records) {
console.log('Borrow records:', records); // Debug log - 确保调用时返回记录的结构
code Copy code
const borrowRecordsList = document.getElementById('borrowRecordsList');
borrowRecordsList.innerHTML = ''; // 清空之前的内容
if (records.length === 0) {
borrowRecordsList.innerHTML = '<p>无借阅记录。</p>';
} else {
const table = document.createElement('table');
table.innerHTML = `
<tr>
<th>用户名</th>
<th>书名</th>
<th>作者</th>
<th>借阅日期</th>
<th>操作</th>
</tr>
`;
records.forEach(record => {
console.log('Record:', record); // 输出每一条记录
const row = document.createElement('tr');
row.innerHTML = `
<td>${record.username}</td>
<td>${record.title}</td>
<td>${record.author}</td>
<td>${record.borrow_date}</td>
<td>
<button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
</td>
`;
table.appendChild(row);
});
borrowRecordsList.appendChild(table);
}
code Copy code
function deleteUser(id) {
fetch(`http://localhost:3000/admin/delete-user`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok: ' + response.statusText);
}
return response.text();
})
.then(data => {
alert(data);
loadUsers(); // 刷新用户列表
})
.catch(error => {
console.error('Error deleting user:', error);
alert('删除用户时出现错误:' + error.message);
});
}
function editUserForm(id) {
fetch(`http://localhost:3000/admin/get-user/${id}`)
.then(response => {
if (!response.ok) {
throw new Error('获取用户信息失败,状态码:' + response.status);
}
return response.json();
})
.then(user => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<form id="editUserForm">
<input type="hidden" value="${id}" name="id">
<input type="text" placeholder="用户名" value="${user.username}" name="username">
<input type="password" placeholder="密码" name="password">
<select name="role">
<option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
<option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
</select>
<button type="button" onclick="editUser(${id})">保存</button>
</form>
`;
})
.catch(error => {
console.error('编辑用户信息获取出错:', error);
alert('获取用户信息失败,请稍后重试:' + error.message);
});
}
function editUser(id) {
const form = document.querySelector(`#editUserForm`);
if (!form || !(form instanceof HTMLFormElement)) {
console.error('Invalid form element');
return;
}
const formData = new FormData(form);
const data = Object.fromEntries(formData.entries());
// Simple validation for required fields
if (!data.username || !data.password || !data.role) {
alert('请填写所有必填字段');
return;
}
fetch(`http://localhost:3000/admin/edit-user`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
.then(response => response.text())
.then(data => {
alert(data);
loadUsers(); // 刷新用户列表
})
.catch(error => {
console.error('Error editing user:', error);
alert('编辑用户信息时出现错误,请稍后重试:' + error.message);
});
}
function editBookForm(bookId) {
// 先调用获取所有图书的后端路由以获取图书数据
fetch('http://localhost:3000/admin/get-books')
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch all books data');
}
return response.json();
})
.then(allBooks => {
// 在获取到的所有图书数据中查找对应id的图书
const targetBook = allBooks.find(book => book.id === Number(bookId));
if (!targetBook) {
alert('未找到对应图书信息,请确认图书ID是否正确');
return;
}
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2>修改图书</h2>
<input type="text" placeholder="旧书名" id="oldTitle" value="${targetBook.title}" disabled>
<input type="text" placeholder="新书名" id="newTitle">
<input type="text" placeholder="新作者" id="newAuthor">
<input type="number" placeholder="新出版年份" id="newYearPublished">
<button onclick="editBook()">保存</button>
`;
})
.catch(error => {
console.error('Error fetching book data:', error);
alert('获取图书信息失败,请稍后重试:' + error.message);
});
code Copy code
function deleteBookConfirm(bookId) {
if (!bookId) {
alert('无效的图书ID');
return;
}
if (confirm(`确定要删除图书ID为${bookId}的图书吗?此操作不可撤销!`)) {
deleteBook(bookId);
}
function deleteBook(bookId) {
if (!bookId) {
alert('无效的图书ID');
return;
}
code Copy code
fetch('http://localhost:3000/admin/delete-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ id: bookId }) // 使用书籍 ID
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Book deleted:', data);
alert('图书删除成功');
loadBooks(); // 重新加载图书列表
})
.catch(error => {
console.error('Error deleting book:', error);
alert('删除图书时出错:' + error.message);
});
function editBook() {
const newTitle = document.getElementById('newTitle').value.trim();
const newAuthor = document.getElementById('newAuthor').value.trim();
const newYearPublished = document.getElementById('newYearPublished').value.trim();
code Copy code
// 简单验证输入框是否为空
if (!newTitle || !newAuthor || !newYearPublished) {
alert('请填写所有修改信息');
return;
}
const oldTitle = document.getElementById('oldTitle').value; // 注意,没有trim(),因为oldTitle是禁用输入,不应更改
fetch('http://localhost:3000/admin/edit-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ oldTitle, newTitle, newAuthor, newYearPublished })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok: ' + response.statusText);
}
return response.text();
})
.then(data => {
console.log('Book edited:', data);
alert('图书修改成功');
showForm('dataManagement'); // 返回数据管理界面
})
.catch(error => {
console.error('Error editing book:', error);
alert('修改图书时出错:' + error.message);
});
}
function deleteBorrowRecordConfirm(recordId) {
console.log('Attempting to delete record with ID:', recordId);
if (!recordId) {
alert('无效的借阅记录ID');
return;
}
if (confirm(确定要删除借阅记录ID为${recordId}的记录吗?此操作不可撤销!)) {
deleteBorrowRecord(recordId);
}
}
function deleteBorrowRecord(recordId) {
fetch('http://localhost:3000/admin/delete-borrow-record ', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ id: recordId }) // 发送要删除记录的 ID
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Borrow record deleted:', data);
alert('借阅记录删除成功');
loadBorrowRecords(); // 重新加载借阅记录列表
})
.catch(error => {
console.error('Error deleting borrow record:', error);
alert('删除借阅记录时出错:' + error.message);
});
}
const app = express();
app.use(cors());
app.use(bodyParser.json());
// MySQL数据库连接配置
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456', // 替换为你的MySQL密码
database: 'librarysystem'
});
db.connect(err => {
if (err) {
throw err;
}
console.log('MySQL connected...');
});
// 登录路由
app.post('/login', (req, res) => {
const { username, password } = req.body;
const query = 'SELECT * FROM users WHERE username = ? AND password = ?';
db.query(query, [username, password], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
console.log("Login successful, sending response:", results[0]);
res.json(results[0]);
} else {
res.status(400).json({ error: 'Invalid login' });
}
});
});
// 注册路由
app.post('/register', (req, res) => {
const { username, password } = req.body;
// 检查用户名是否已存在
const checkUserQuery = 'SELECT * FROM users WHERE username = ?';
db.query(checkUserQuery, [username], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
// 用户名已存在
res.status(400).json({ error: 'Username already exists' });
} else {
// 用户名不存在,可以注册
const insertUserQuery = 'INSERT INTO users (username, password, role) VALUES (?, ?, ?)';
db.query(insertUserQuery, [username, password, 'user'], (err, results) => {
if (err) {
res.status(500).json({ error: 'Failed to register user' });
} else {
res.status(201).send('User registered successfully');
}
});
}
});
});
// 管理员操作路由
// 添加图书
app.post('/admin/add-book', (req, res) => {
const { title, author, year_published } = req.body;
const query = 'INSERT INTO books (title, author, year_published) VALUES (?, ?, ?)';
db.query(query, [title, author, year_published], (err, results) => {
if (err) {
console.error('Error adding book:', err);
res.status(500).json({ error: 'Failed to add book' });
} else {
res.status(200).send('Book added successfully');
}
});
});
// 删除图书
app.post('/admin/delete-book', (req, res) => {
const { id } = req.body;
code Copy code
// 确保 ID 是有效的数字
if (!id || isNaN(id)) {
res.status(400).json({ error: 'Invalid book ID format' });
return;
}
const query = 'DELETE FROM books WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error deleting book:', err);
res.status(500).json({ error: 'Failed to delete book. Error details: ' + err.message });
} else {
// 检查是否有行被删除
if (results.affectedRows > 0) {
res.send('Book deleted');
} else {
res.status(404).send('No book found with this ID');
}
}
});
// 用户操作路由
// 搜索书籍
app.post('/user/search-books', (req, res) => {
const { keyword } = req.body;
const query = SELECT * FROM books WHERE id = ? OR title LIKE ? OR author LIKE ? ;
db.query(query, [keyword, %${keyword}%, %${keyword}%], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 添加收藏
// 获取用户的收藏书籍
app.get('/user/favorites/:userId', (req, res) => {
const { userId } = req.params;
const query = SELECT b.id, b.title, b.author FROM favorites f JOIN books b ON f.book_id = b.id WHERE f.user_id = ? ;
db.query(query, [userId], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 编辑图书
app.post('/admin/edit-book', (req, res) => {
const { oldTitle, newTitle, newAuthor, newYearPublished } = req.body;
code Copy code
// 验证每个字段
if (!oldTitle || !newTitle || !newAuthor || !newYearPublished) {
return res.status(400).json({ error: '所有字段都需要填写' });
}
const query = 'UPDATE books SET title=?, author=?, year_published=? WHERE title=?';
db.query(query, [newTitle, newAuthor, newYearPublished, oldTitle], (err, results) => {
if (err) {
console.error('Error editing book:', err);
return res.status(500).json({ error: 'Failed to edit book. Error details: ' + err.message });
}
// 检查是否有行被更新
if (results.affectedRows > 0) {
res.status(200).send('Book edited successfully');
} else {
res.status(404).send('No book found with that title for editing');
}
});
});
app.post('/admin/edit-book', (req, res) => {
const { oldTitle, newTitle, newAuthor, newYearPublished } = req.body;
code Copy code
// 验证每个字段
if (!oldTitle || !newTitle || !newAuthor || !newYearPublished) {
return res.status(400).json({ error: '所有字段都需要填写' });
}
const query = 'UPDATE books SET title=?, author=?, year_published=? WHERE title=?';
db.query(query, [newTitle, newAuthor, newYearPublished, oldTitle], (err, results) => {
if (err) {
console.error('Error editing book:', err);
return res.status(500).json({ error: 'Failed to edit book. Error details: ' + err.message });
}
// 检查是否有行被更新
if (results.affectedRows > 0) {
res.status(200).send('Book edited successfully');
} else {
res.status(404).send('No book found with that title for editing');
}
});
app.get('/admin/get-books', (req, res) => {
const query = 'SELECT * FROM books';
db.query(query, (err, results) => {
if (err) {
console.error('Error getting books:', err);
res.status(500).json({ error: 'Failed to get books' });
} else {
res.json(results);
}
});
});
// 获取所有用户
app.get('/admin/get-users', (req, res) => {
const query = 'SELECT * FROM users';
db.query(query, (err, results) => {
if (err) {
console.error('Error getting users:', err);
res.status(500).json({ error: 'Failed to get users' });
} else {
res.json(results);
}
});
});
// 借阅书籍
app.post('/user/borrow-book', (req, res) => {
const { userId, bookId } = req.body;
const query = 'INSERT INTO borrow_records (user_id, book_id, borrow_date) VALUES (?, ?, NOW())';
db.query(query, [userId, bookId], (err, results) => {
if (err) {
console.error('Error borrowing book:', err);
res.status(500).json({ error: 'Failed to borrow book' });
} else {
res.status(200).send('Book borrowed successfully');
}
});
});
// 获取借阅历史
app.get('/user/borrow-history/:userId', (req, res) => {
const { userId } = req.params;
const query = SELECT b.title, b.author, br.borrow_date FROM borrow_records br JOIN books b ON br.book_id = b.id WHERE br.user_id = ? ORDER BY br.borrow_date DESC ;
db.query(query, [userId], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 获取所有借阅记录(管理员用)
// 获取所有借阅记录(管理员用)
app.get('/admin/borrow-records', (req, res) => {
const query = SELECT br.id, u.username, b.title, b.author, br.borrow_date FROM borrow_records br JOIN users u ON br.user_id = u.id JOIN books b ON br.book_id = b.id ORDER BY br.borrow_date DESC ;
db.query(query, (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
// Ensure that the ID is included in results
res.json(results);
}
});
});
// 编辑用户
app.post('/admin/edit-user', (req, res) => {
const { id, username, password, role } = req.body;
const query = 'UPDATE users SET username =?, password =?, role =? WHERE id =?';
db.query(query, [username, password, role, id], (err, results) => {
if (err) {
console.error('编辑用户信息出错,编辑的用户ID:', id);
console.error('错误信息:', err.message);
console.error('错误堆栈:', err.stack);
res.status(500).json({ error: 'Failed to edit user' });
} else {
console.log('用户信息编辑成功,编辑的用户ID:', id);
res.status(200).send('User edited successfully');
}
});
});
// 删除图书通过书名
app.post('/admin/delete-book-by-title', (req, res) => {
const { title } = req.body; // 获取书名
code Copy code
// 确保书名是有效的字符串
if (!title || typeof title !== 'string') {
return res.status(400).json({ error: 'Invalid book title format' });
}
// SQL 查询使用书名删除图书
const query = 'DELETE FROM books WHERE title = ?';
db.query(query, [title], (err, results) => {
if (err) {
console.error('Error deleting book:', err);
return res.status(500).json({ error: 'Failed to delete book. Error details: ' + err.message });
} else {
if (results.affectedRows > 0) {
res.send('Book deleted');
} else {
res.status(404).send('No book found with that title');
}
}
});
});
// 删除用户
app.post('/admin/delete-user', (req, res) => {
const { id } = req.body;
db.beginTransaction((err => {
if (err) {
console.error('Error starting transaction:', err);
res.status(500).send('Server error starting transaction');
return;
}
// 先删除 borrow_records 表中与该用户相关的记录
const deleteBorrowRecordsQuery = 'DELETE FROM borrow_records WHERE user_id =?';
db.query(deleteBorrowRecordsQuery, [id], (err => {
if (err) {
db.rollback(() => {
console.error('Error deleting related borrow records, rolling back transaction:', err);
res.status(500).send('Server error when deleting related borrow records, transaction rolled back');
});
return;
}
// 再删除 favorites 表中与该用户相关的记录
const deleteFavoritesQuery = 'DELETE FROM favorites WHERE user_id =?';
db.query(deleteFavoritesQuery, [id], (err => {
if (err) {
db.rollback(() => {
console.error('Error deleting related favorites, rolling back transaction:', err);
res.status(500).send('Server error when deleting related favorites, transaction rolled back');
});
return;
}
// 最后执行删除用户操作
const query = 'DELETE FROM users WHERE id =?';
db.query(query, [id], (err, results) => {
if (err) {
db.rollback(() => {
console.error('删除用户出错,要删除的用户ID:', id);
console.error('错误信息:', err.message);
console.error('错误堆栈:', err.stack);
res.status(500).send('Server error, transaction rolled back');
});
} else {
db.commit((err => {
if (err) {
console.error('Error committing transaction:', err);
res.status(500).send('Server error committing transaction');
return;
}
console.log('用户删除成功,删除的用户ID:', id);
res.send('User deleted');
}));
}
});
}));
}));
}));
});
//获取单个用户
app.get('/admin/get-user/:id', (req, res) => {
const { id } = req.params;
const query = 'SELECT * FROM users WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error getting user:', err);
res.status(500).json({ error: 'Failed to get user' });
} else if (results.length === 0) {
res.status(404).json({ error: 'User not found' });
} else {
res.json(results[0]);
}
});
});
// 编辑借阅记录(注意:通常借阅记录不需要编辑,但这里为了完整性提供示例)
app.post('/admin/edit-borrow-record', (req, res) => {
const { id, user_id, book_id, borrow_date } = req.body;
const query = 'UPDATE borrow_records SET user_id = ?, book_id = ?, borrow_date = ? WHERE id = ?';
db.query(query, [user_id, book_id, borrow_date, id], (err, results) => {
if (err) {
console.error('Error editing borrow record:', err);
res.status(500).json({ error: 'Failed to edit borrow record' });
} else {
res.status(200).send('Borrow record edited successfully');
}
});
});
// 删除借阅记录
app.post('/admin/delete-borrow-record', (req, res) => {
const { id } = req.body;
code Copy code
if (!id || isNaN(id)) {
return res.status(400).send('无效的借阅记录ID格式');
}
const query = 'DELETE FROM borrow_records WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error deleting borrow record:', err);
return res.status(500).send('服务器错误');
}
if (results.affectedRows > 0) {
res.send('借阅记录删除成功');
} else {
res.status(404).send('没有找到该借阅记录');
}
});
});
// 获取单个借阅记录详情的路由
app.get('/admin/get-borrow-record/:id', (req, res) => {
const { id } = req.params;
// 验证id是否为有效的数字且大于0
if (!Number.isInteger(Number(id)) || Number(id) <= 0) {
res.status(400).json({ error: 'Invalid borrow record ID format or value' });
return;
}
const query = SELECT * FROM borrow_records WHERE id =? ;
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error getting borrow record:', err);
res.status(500).json({ error: 'Failed to get borrow record. Error details: ' + err.message });
} else if (results.length === 0) {
res.status(404).json({ error: 'Borrow record not found' });
} else {
res.json(results[0]);
}
});
});
// 添加收藏路由
app.post('/user/add-favorite', (req, res) => {
const { userId, bookId } = req.body;
// 先检查该用户是否已经收藏了这本书
const checkFavoriteQuery = 'SELECT * FROM favorites WHERE user_id =? AND book_id =?';
db.query(checkFavoriteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
// 已收藏,提示用户
res.status(400).json({ error: 'This book has already been added to favorites' });
} else {
// 可以添加收藏,插入记录到 favorites 表
const insertFavoriteQuery = 'INSERT INTO favorites (user_id, book_id) VALUES (?,?)';
db.query(insertFavoriteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Failed to add to favorites' });
} else {
// 返回成功的 JSON 响应
res.status(200).json({ message: 'Book added to favorites successfully' });
}
});
}
});
});
// 删除收藏书籍路由
app.post('/user/delete-favorite', (req, res) => {
const { userId, bookId } = req.body;
const deleteQuery = 'DELETE FROM favorites WHERE user_id =? AND book_id =?';
db.query(deleteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error when deleting favorite' });
} else if (results.affectedRows === 0) {
// 如果受影响的行数为0,表示没有找到对应的收藏记录,即可能已经不存在该收藏了
res.status(400).json({ error: 'This book is not in your favorites' });
} else {
res.status(200).json({ message: 'Book removed from favorites successfully' });
}
});
});
// 从收藏中借阅书籍
app.post('/user/borrow-from-favorite', (req, res) => {
const { userId, bookId } = req.body;
// 先从收藏中删除这本书
const deleteFavoriteQuery = 'DELETE FROM favorites WHERE user_id = ? AND book_id = ?';
db.query(deleteFavoriteQuery, [userId, bookId], (err, deleteResults) => {
if (err) {
console.error('Error deleting favorite before borrowing:', err);
res.status(500).json({ error: 'Failed to borrow book from favorites' });
return;
}
if (deleteResults.affectedRows === 0) {
res.status(400).json({ error: 'This book is not in your favorites' });
return;
}
code Copy code
// 然后借阅这本书
const borrowQuery = 'INSERT INTO borrow_records (user_id, book_id, borrow_date) VALUES (?, ?, NOW())';
db.query(borrowQuery, [userId, bookId], (err, borrowResults) => {
if (err) {
console.error('Error borrowing book:', err);
res.status(500).json({ error: 'Failed to borrow book' });
} else {
// 返回成功的 JSON 响应
res.status(200).json({ message: 'Book borrowed from favorites successfully' });
}
});
});
// 监听端口
const PORT = 3000;
app.listen(PORT, () => {
console.log(Server running on port ${PORT});
});修改删除图书模块,让他只能删除id改为按照书名删除
3. 修改后端代码 在后端,我们需要添加一个新的路由来处理通过书名删除书籍的请求。
javascript Copy code
// 删除图书通过书名
app.post('/admin/delete-book-by-title', (req, res) => {
const { title } = req.body; // 获取书名
// 确保书名是有效的字符串
if (!title || typeof title !== 'string') {
return res.status(400).json({ error: 'Invalid book title format' });
}
// SQL 查询使用书名删除图书
const query = 'DELETE FROM books WHERE title = ?';
db.query(query, [title], (err, results) => {
if (err) {
console.error('Error deleting book:', err);
return res.status(500).json({ error: 'Failed to delete book. Error details: ' + err.message });
} else {
if (results.affectedRows > 0) {
res.send('Book deleted');
} else {
res.status(404).send('No book found with that title');
}
}
});
});
4. 完整示例 请确保在 Node.js 服务中添加新的路由 delete-book-by-title,并更新前端以使用该新功能。
测试
运行 Node.js 服务器。
打开管理员页面,尝试使用书名删除图书。
确保在数据库中存在输入的书名,并确保能够从数据库中成功删除。
这样就完成了从图书管理中基于书名删除图书的实现。确保在生产环境中加入合适的错误处理和安全性考虑。
// 根据type动态创建表单
switch (type) {
case 'add':
formContainer.innerHTML = `
<input type="text" placeholder="书名">
<input type="text" placeholder="作者">
<input type="number" placeholder="出版年份">
<button onclick="addBook()">添加</button>
`;
break;
case 'delete':
formContainer.innerHTML = `
<h2>删除图书</h2>
<input type="text" id="bookTitle" placeholder="输入书名" style="width: 200px;" />
<button onclick="deleteBook()">删除</button>
`;
break;
case 'borrowRecords':
formContainer.innerHTML = `<h2>借阅记录</h2><div id="borrowRecordsList"></div>`;
loadBorrowRecords();
break;
case 'edit':
formContainer.innerHTML = `
<h2>修改图书</h2>
<input type="text" placeholder="旧书名" id="oldTitle">
<input type="text" placeholder="新书名" id="newTitle">
<input type="text" placeholder="新作者" id="newAuthor">
<input type="number" placeholder="新出版年份" id="newYearPublished">
<button onclick="editBook()">修改</button>
`;
break;
case 'search':
formContainer.innerHTML = `
<input type="text" placeholder="搜索关键词" id="searchKeyword">
<button onclick="searchBooks()">查询</button>
`;
break;
case 'userManagement':
loadUsers().then(users => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">用户管理</h2>
<div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
<ul style="list-style-type: none; padding: 0;">
`;
users.forEach(user => {
formContainer.innerHTML += `
<li style="margin: 10px 0;">
${user.username}
<button onclick="editUserForm('${user.id}')">编辑</button>
<button onclick="deleteUser('${user.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
});
break;
case 'dataManagement':
formContainer.innerHTML = `
<h2>数据管理</h2>
<!-- 这里可以添加数据管理的相关表单或内容 -->
`;
loadBooks(); // 正确的位置
break;
case 'borrowRecords':
formContainer.innerHTML = `
<h2>借阅记录</h2>
<!-- 这里可以添加借阅记录的相关表单或内容 -->
`;
break;
case 'editUser':
fetch(`http://localhost:3000/admin/get-user/${id}`)
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch user data');
}
return response.json();
})
.then(user => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<input type="hidden" value="${id}" name="id">
<input type="text" placeholder="用户名" value="${user.username}" name="username">
<input type="password" placeholder="密码" name="password">
<select name="role">
<option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
<option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
</select>
<button onclick="editUser(${id})">保存</button>
`;
})
.catch(error => {
console.error('Error fetching user data:', error);
alert('Failed to fetch user data: ' + error.message);
});
break;
case 'deleteUser':
if (confirm(`确定要删除用户ID为${id}的用户吗?此操作不可撤销!`)) {
deleteUser(id);
}
break;
case 'deleteByTitle':
formContainer.innerHTML = `
<h2>删除图书</h2>
<input type="text" id="bookTitle" placeholder="输入书名" style="width: 200px;" />
<button onclick="deleteBookByTitle()">删除</button>
`;
break;
default:
formContainer.style.display = 'none';
}
}
//删除图书
function deleteBookByTitle() {
const bookTitle = document.getElementById('bookTitle').value; // 获取书名
if (!bookTitle) {
alert('请输入书名以进行删除');
return;
}
fetch('http://localhost:3000/admin/delete-book-by-title', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ title: bookTitle }) // 传递书名
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Book deleted:', data);
alert('图书删除成功');
loadBooks(); // 重新加载图书列表
})
.catch(error => {
console.error('Error deleting book:', error);
alert('删除图书时出错:' + error.message);
});
}
function addBook() {
// 获取表单数据
const formContainer = document.getElementById('formContainer');
const title = formContainer.querySelector('input[placeholder="书名"]').value;
const author = formContainer.querySelector('input[placeholder="作者"]').value;
const year_published = formContainer.querySelector('input[placeholder="出版年份"]').value; // 使用正确的变量名
code Copy code
// 发送增加图书的请求
fetch('http://localhost:3000/admin/add-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin' // 假设已经在某处设置了用户类型
},
body: JSON.stringify({ title, author, year_published }) // 使用正确的变量名
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Book added:', data);
alert('图书添加成功:' + data); // 显示成功消息
// 可选:清空表单
formContainer.innerHTML = '';
formContainer.style.display = 'none';
// 可选:更新图书列表(如果有的话)
})
.catch(error => {
console.error('Error adding book:', error);
alert('添加图书时出错:' + error.message);
});
}
function searchBooks() {
const searchKeyword = document.getElementById('searchKeyword').value;
fetch('http://localhost:3000/user/search-books', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ keyword: searchKeyword })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
displaySearchResults(data);
})
.catch(error => {
console.error('Error searching books:', error);
alert('搜索图书时出错:' + error.message);
});
}
function displaySearchResults(books) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<div>
<button onclick="showForm('search')">返回继续搜索</button>
</div>
<h2>搜索结果</h2>
`;
if (books.length === 0) {
formContainer.innerHTML += '<p>未找到图书。</p>';
} else {
const resultsList = document.createElement('ul');
books.forEach(book => {
const listItem = document.createElement('li');
listItem.textContent = `${book.title} by ${book.author} (${book.year_published})`;
resultsList.appendChild(listItem);
});
formContainer.appendChild(resultsList);
}
}
function loadBooks() {
console.log('Starting to load books...');
return fetch('http://localhost:3000/admin/get-books')
.then(response => {
console.log('Received response from get-books:', response);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(books => {
console.log('Loaded books data:', books);
displayBooks(books);
return Promise.resolve(); // 显式返回一个已解决的Promise,确保外层能正确链式调用
})
.catch(error => {
console.error('Error loading books:', error);
alert('加载图书时出错:' + error.message);
return Promise.reject(error); // 出现错误时返回一个被拒绝的Promise,传播错误
});
}
function displayBooks(books) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">图书管理</h2>
<div class="book-list-container">
<ul>
`;
books.forEach(book => {
formContainer.innerHTML += `
<li>
${book.title} by ${book.author} (${book.year_published})
<button onclick="editBookForm('${book.id}')">编辑</button>
<button onclick="deleteBookConfirm('${book.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
return Promise.resolve();
code Copy code
function loadUsers() {
return fetch('http://localhost:3000/admin/get-users')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(users => {
displayUsers(users);
return users; // 将处理后的用户数据返回,使得外层能接收到这个 Promise 结果
})
.catch(error => {
console.error('Error loading users:', error);
alert('加载用户时出错:' + error.message);
throw error; // 可以选择重新抛出错误,让调用处能进一步处理
});
}
function displayUsers(users) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">用户管理</h2>
<div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
<ul style="list-style-type: none; padding: 0;">
`;
users.forEach(user => {
formContainer.innerHTML += `
<li style="margin: 10px 0;">
${user.username}
<button onclick="editUserForm('${user.id}')">编辑</button>
<button onclick="deleteUserConfirm('${user.id}')">删除</button>
</li>
`;
});
formContainer.innerHTML += `
</ul>
</div>
`;
}
function loadBorrowRecords() {
fetch('http://localhost:3000/admin/borrow-records') // 确保此 API 地址是正确的
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(records => {
console.log('Loaded borrow records:', records); // 检查返回的 records
displayBorrowRecords(records);
})
.catch(error => {
console.error('Error loading borrow records:', error);
alert('加载借阅记录时出错:' + error.message);
});
function displayBorrowRecords(records) {
console.log('Borrow records:', records); // Debug log - 确保调用时返回记录的结构
code Copy code
const borrowRecordsList = document.getElementById('borrowRecordsList');
borrowRecordsList.innerHTML = ''; // 清空之前的内容
if (records.length === 0) {
borrowRecordsList.innerHTML = '<p>无借阅记录。</p>';
} else {
const table = document.createElement('table');
table.innerHTML = `
<tr>
<th>用户名</th>
<th>书名</th>
<th>作者</th>
<th>借阅日期</th>
<th>操作</th>
</tr>
`;
records.forEach(record => {
console.log('Record:', record); // 输出每一条记录
const row = document.createElement('tr');
row.innerHTML = `
<td>${record.username}</td>
<td>${record.title}</td>
<td>${record.author}</td>
<td>${record.borrow_date}</td>
<td>
<button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
</td>
`;
table.appendChild(row);
});
borrowRecordsList.appendChild(table);
}
code Copy code
function deleteUser(id) {
fetch(`http://localhost:3000/admin/delete-user`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok: ' + response.statusText);
}
return response.text();
})
.then(data => {
alert(data);
loadUsers(); // 刷新用户列表
})
.catch(error => {
console.error('Error deleting user:', error);
alert('删除用户时出现错误:' + error.message);
});
}
function editUserForm(id) {
fetch(`http://localhost:3000/admin/get-user/${id}`)
.then(response => {
if (!response.ok) {
throw new Error('获取用户信息失败,状态码:' + response.status);
}
return response.json();
})
.then(user => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<form id="editUserForm">
<input type="hidden" value="${id}" name="id">
<input type="text" placeholder="用户名" value="${user.username}" name="username">
<input type="password" placeholder="密码" name="password">
<select name="role">
<option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
<option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
</select>
<button type="button" onclick="editUser(${id})">保存</button>
</form>
`;
})
.catch(error => {
console.error('编辑用户信息获取出错:', error);
alert('获取用户信息失败,请稍后重试:' + error.message);
});
}
function editUser(id) {
const form = document.querySelector(`#editUserForm`);
if (!form || !(form instanceof HTMLFormElement)) {
console.error('Invalid form element');
return;
}
const formData = new FormData(form);
const data = Object.fromEntries(formData.entries());
// Simple validation for required fields
if (!data.username || !data.password || !data.role) {
alert('请填写所有必填字段');
return;
}
fetch(`http://localhost:3000/admin/edit-user`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
.then(response => response.text())
.then(data => {
alert(data);
loadUsers(); // 刷新用户列表
})
.catch(error => {
console.error('Error editing user:', error);
alert('编辑用户信息时出现错误,请稍后重试:' + error.message);
});
}
function editBookForm(bookId) {
// 先调用获取所有图书的后端路由以获取图书数据
fetch('http://localhost:3000/admin/get-books')
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch all books data');
}
return response.json();
})
.then(allBooks => {
// 在获取到的所有图书数据中查找对应id的图书
const targetBook = allBooks.find(book => book.id === Number(bookId));
if (!targetBook) {
alert('未找到对应图书信息,请确认图书ID是否正确');
return;
}
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2>修改图书</h2>
<input type="text" placeholder="旧书名" id="oldTitle" value="${targetBook.title}" disabled>
<input type="text" placeholder="新书名" id="newTitle">
<input type="text" placeholder="新作者" id="newAuthor">
<input type="number" placeholder="新出版年份" id="newYearPublished">
<button onclick="editBook()">保存</button>
`;
})
.catch(error => {
console.error('Error fetching book data:', error);
alert('获取图书信息失败,请稍后重试:' + error.message);
});
code Copy code
function deleteBookConfirm(bookId) {
if (!bookId) {
alert('无效的图书ID');
return;
}
if (confirm(`确定要删除图书ID为${bookId}的图书吗?此操作不可撤销!`)) {
deleteBook(bookId);
}
function deleteBook(bookId) {
if (!bookId) {
alert('无效的图书ID');
return;
}
code Copy code
fetch('http://localhost:3000/admin/delete-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ id: bookId }) // 使用书籍 ID
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Book deleted:', data);
alert('图书删除成功');
loadBooks(); // 重新加载图书列表
})
.catch(error => {
console.error('Error deleting book:', error);
alert('删除图书时出错:' + error.message);
});
function editBook() {
const newTitle = document.getElementById('newTitle').value.trim();
const newAuthor = document.getElementById('newAuthor').value.trim();
const newYearPublished = document.getElementById('newYearPublished').value.trim();
code Copy code
// 简单验证输入框是否为空
if (!newTitle || !newAuthor || !newYearPublished) {
alert('请填写所有修改信息');
return;
}
const oldTitle = document.getElementById('oldTitle').value; // 注意,没有trim(),因为oldTitle是禁用输入,不应更改
fetch('http://localhost:3000/admin/edit-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ oldTitle, newTitle, newAuthor, newYearPublished })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok: ' + response.statusText);
}
return response.text();
})
.then(data => {
console.log('Book edited:', data);
alert('图书修改成功');
showForm('dataManagement'); // 返回数据管理界面
})
.catch(error => {
console.error('Error editing book:', error);
alert('修改图书时出错:' + error.message);
});
}
function deleteBorrowRecordConfirm(recordId) {
console.log('Attempting to delete record with ID:', recordId);
if (!recordId) {
alert('无效的借阅记录ID');
return;
}
if (confirm(确定要删除借阅记录ID为${recordId}的记录吗?此操作不可撤销!)) {
deleteBorrowRecord(recordId);
}
}
function deleteBorrowRecord(recordId) {
fetch('http://localhost:3000/admin/delete-borrow-record ', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ id: recordId }) // 发送要删除记录的 ID
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log('Borrow record deleted:', data);
alert('借阅记录删除成功');
loadBorrowRecords(); // 重新加载借阅记录列表
})
.catch(error => {
console.error('Error deleting borrow record:', error);
alert('删除借阅记录时出错:' + error.message);
});
}
const app = express();
app.use(cors());
app.use(bodyParser.json());
// MySQL数据库连接配置
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456', // 替换为你的MySQL密码
database: 'librarysystem'
});
db.connect(err => {
if (err) {
throw err;
}
console.log('MySQL connected...');
});
// 登录路由
app.post('/login', (req, res) => {
const { username, password } = req.body;
const query = 'SELECT * FROM users WHERE username = ? AND password = ?';
db.query(query, [username, password], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
console.log("Login successful, sending response:", results[0]);
res.json(results[0]);
} else {
res.status(400).json({ error: 'Invalid login' });
}
});
});
// 注册路由
app.post('/register', (req, res) => {
const { username, password } = req.body;
// 检查用户名是否已存在
const checkUserQuery = 'SELECT * FROM users WHERE username = ?';
db.query(checkUserQuery, [username], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
// 用户名已存在
res.status(400).json({ error: 'Username already exists' });
} else {
// 用户名不存在,可以注册
const insertUserQuery = 'INSERT INTO users (username, password, role) VALUES (?, ?, ?)';
db.query(insertUserQuery, [username, password, 'user'], (err, results) => {
if (err) {
res.status(500).json({ error: 'Failed to register user' });
} else {
res.status(201).send('User registered successfully');
}
});
}
});
});
// 管理员操作路由
// 添加图书
app.post('/admin/add-book', (req, res) => {
const { title, author, year_published } = req.body;
const query = 'INSERT INTO books (title, author, year_published) VALUES (?, ?, ?)';
db.query(query, [title, author, year_published], (err, results) => {
if (err) {
console.error('Error adding book:', err);
res.status(500).json({ error: 'Failed to add book' });
} else {
res.status(200).send('Book added successfully');
}
});
});
// 删除图书
app.post('/admin/delete-book', (req, res) => {
const { id } = req.body;
code Copy code
// 确保 ID 是有效的数字
if (!id || isNaN(id)) {
res.status(400).json({ error: 'Invalid book ID format' });
return;
}
const query = 'DELETE FROM books WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error deleting book:', err);
res.status(500).json({ error: 'Failed to delete book. Error details: ' + err.message });
} else {
// 检查是否有行被删除
if (results.affectedRows > 0) {
res.send('Book deleted');
} else {
res.status(404).send('No book found with this ID');
}
}
});
// 用户操作路由
// 搜索书籍
app.post('/user/search-books', (req, res) => {
const { keyword } = req.body;
const query = SELECT * FROM books WHERE id = ? OR title LIKE ? OR author LIKE ? ;
db.query(query, [keyword, %${keyword}%, %${keyword}%], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 添加收藏
// 获取用户的收藏书籍
app.get('/user/favorites/:userId', (req, res) => {
const { userId } = req.params;
const query = SELECT b.id, b.title, b.author FROM favorites f JOIN books b ON f.book_id = b.id WHERE f.user_id = ? ;
db.query(query, [userId], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 编辑图书
app.post('/admin/edit-book', (req, res) => {
const { oldTitle, newTitle, newAuthor, newYearPublished } = req.body;
code Copy code
// 验证每个字段
if (!oldTitle || !newTitle || !newAuthor || !newYearPublished) {
return res.status(400).json({ error: '所有字段都需要填写' });
}
const query = 'UPDATE books SET title=?, author=?, year_published=? WHERE title=?';
db.query(query, [newTitle, newAuthor, newYearPublished, oldTitle], (err, results) => {
if (err) {
console.error('Error editing book:', err);
return res.status(500).json({ error: 'Failed to edit book. Error details: ' + err.message });
}
// 检查是否有行被更新
if (results.affectedRows > 0) {
res.status(200).send('Book edited successfully');
} else {
res.status(404).send('No book found with that title for editing');
}
});
});
app.post('/admin/edit-book', (req, res) => {
const { oldTitle, newTitle, newAuthor, newYearPublished } = req.body;
code Copy code
// 验证每个字段
if (!oldTitle || !newTitle || !newAuthor || !newYearPublished) {
return res.status(400).json({ error: '所有字段都需要填写' });
}
const query = 'UPDATE books SET title=?, author=?, year_published=? WHERE title=?';
db.query(query, [newTitle, newAuthor, newYearPublished, oldTitle], (err, results) => {
if (err) {
console.error('Error editing book:', err);
return res.status(500).json({ error: 'Failed to edit book. Error details: ' + err.message });
}
// 检查是否有行被更新
if (results.affectedRows > 0) {
res.status(200).send('Book edited successfully');
} else {
res.status(404).send('No book found with that title for editing');
}
});
app.get('/admin/get-books', (req, res) => {
const query = 'SELECT * FROM books';
db.query(query, (err, results) => {
if (err) {
console.error('Error getting books:', err);
res.status(500).json({ error: 'Failed to get books' });
} else {
res.json(results);
}
});
});
// 获取所有用户
app.get('/admin/get-users', (req, res) => {
const query = 'SELECT * FROM users';
db.query(query, (err, results) => {
if (err) {
console.error('Error getting users:', err);
res.status(500).json({ error: 'Failed to get users' });
} else {
res.json(results);
}
});
});
// 借阅书籍
app.post('/user/borrow-book', (req, res) => {
const { userId, bookId } = req.body;
const query = 'INSERT INTO borrow_records (user_id, book_id, borrow_date) VALUES (?, ?, NOW())';
db.query(query, [userId, bookId], (err, results) => {
if (err) {
console.error('Error borrowing book:', err);
res.status(500).json({ error: 'Failed to borrow book' });
} else {
res.status(200).send('Book borrowed successfully');
}
});
});
// 获取借阅历史
app.get('/user/borrow-history/:userId', (req, res) => {
const { userId } = req.params;
const query = SELECT b.title, b.author, br.borrow_date FROM borrow_records br JOIN books b ON br.book_id = b.id WHERE br.user_id = ? ORDER BY br.borrow_date DESC ;
db.query(query, [userId], (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
res.json(results);
}
});
});
// 获取所有借阅记录(管理员用)
// 获取所有借阅记录(管理员用)
app.get('/admin/borrow-records', (req, res) => {
const query = SELECT br.id, u.username, b.title, b.author, br.borrow_date FROM borrow_records br JOIN users u ON br.user_id = u.id JOIN books b ON br.book_id = b.id ORDER BY br.borrow_date DESC ;
db.query(query, (err, results) => {
if (err) {
res.status(500).send('Server error');
} else {
// Ensure that the ID is included in results
res.json(results);
}
});
});
// 编辑用户
app.post('/admin/edit-user', (req, res) => {
const { id, username, password, role } = req.body;
const query = 'UPDATE users SET username =?, password =?, role =? WHERE id =?';
db.query(query, [username, password, role, id], (err, results) => {
if (err) {
console.error('编辑用户信息出错,编辑的用户ID:', id);
console.error('错误信息:', err.message);
console.error('错误堆栈:', err.stack);
res.status(500).json({ error: 'Failed to edit user' });
} else {
console.log('用户信息编辑成功,编辑的用户ID:', id);
res.status(200).send('User edited successfully');
}
});
});
// 删除图书通过书名
app.post('/admin/delete-book-by-title', (req, res) => {
const { title } = req.body; // 获取书名
code Copy code
// 确保书名是有效的字符串
if (!title || typeof title !== 'string') {
return res.status(400).json({ error: 'Invalid book title format' });
}
// SQL 查询使用书名删除图书
const query = 'DELETE FROM books WHERE title = ?';
db.query(query, [title], (err, results) => {
if (err) {
console.error('Error deleting book:', err);
return res.status(500).json({ error: 'Failed to delete book. Error details: ' + err.message });
} else {
if (results.affectedRows > 0) {
res.send('Book deleted');
} else {
res.status(404).send('No book found with that title');
}
}
});
});
// 删除用户
app.post('/admin/delete-user', (req, res) => {
const { id } = req.body;
db.beginTransaction((err => {
if (err) {
console.error('Error starting transaction:', err);
res.status(500).send('Server error starting transaction');
return;
}
// 先删除 borrow_records 表中与该用户相关的记录
const deleteBorrowRecordsQuery = 'DELETE FROM borrow_records WHERE user_id =?';
db.query(deleteBorrowRecordsQuery, [id], (err => {
if (err) {
db.rollback(() => {
console.error('Error deleting related borrow records, rolling back transaction:', err);
res.status(500).send('Server error when deleting related borrow records, transaction rolled back');
});
return;
}
// 再删除 favorites 表中与该用户相关的记录
const deleteFavoritesQuery = 'DELETE FROM favorites WHERE user_id =?';
db.query(deleteFavoritesQuery, [id], (err => {
if (err) {
db.rollback(() => {
console.error('Error deleting related favorites, rolling back transaction:', err);
res.status(500).send('Server error when deleting related favorites, transaction rolled back');
});
return;
}
// 最后执行删除用户操作
const query = 'DELETE FROM users WHERE id =?';
db.query(query, [id], (err, results) => {
if (err) {
db.rollback(() => {
console.error('删除用户出错,要删除的用户ID:', id);
console.error('错误信息:', err.message);
console.error('错误堆栈:', err.stack);
res.status(500).send('Server error, transaction rolled back');
});
} else {
db.commit((err => {
if (err) {
console.error('Error committing transaction:', err);
res.status(500).send('Server error committing transaction');
return;
}
console.log('用户删除成功,删除的用户ID:', id);
res.send('User deleted');
}));
}
});
}));
}));
}));
});
//获取单个用户
app.get('/admin/get-user/:id', (req, res) => {
const { id } = req.params;
const query = 'SELECT * FROM users WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error getting user:', err);
res.status(500).json({ error: 'Failed to get user' });
} else if (results.length === 0) {
res.status(404).json({ error: 'User not found' });
} else {
res.json(results[0]);
}
});
});
// 编辑借阅记录(注意:通常借阅记录不需要编辑,但这里为了完整性提供示例)
app.post('/admin/edit-borrow-record', (req, res) => {
const { id, user_id, book_id, borrow_date } = req.body;
const query = 'UPDATE borrow_records SET user_id = ?, book_id = ?, borrow_date = ? WHERE id = ?';
db.query(query, [user_id, book_id, borrow_date, id], (err, results) => {
if (err) {
console.error('Error editing borrow record:', err);
res.status(500).json({ error: 'Failed to edit borrow record' });
} else {
res.status(200).send('Borrow record edited successfully');
}
});
});
// 删除借阅记录
app.post('/admin/delete-borrow-record', (req, res) => {
const { id } = req.body;
code Copy code
if (!id || isNaN(id)) {
return res.status(400).send('无效的借阅记录ID格式');
}
const query = 'DELETE FROM borrow_records WHERE id = ?';
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error deleting borrow record:', err);
return res.status(500).send('服务器错误');
}
if (results.affectedRows > 0) {
res.send('借阅记录删除成功');
} else {
res.status(404).send('没有找到该借阅记录');
}
});
});
// 获取单个借阅记录详情的路由
app.get('/admin/get-borrow-record/:id', (req, res) => {
const { id } = req.params;
// 验证id是否为有效的数字且大于0
if (!Number.isInteger(Number(id)) || Number(id) <= 0) {
res.status(400).json({ error: 'Invalid borrow record ID format or value' });
return;
}
const query = SELECT * FROM borrow_records WHERE id =? ;
db.query(query, [id], (err, results) => {
if (err) {
console.error('Error getting borrow record:', err);
res.status(500).json({ error: 'Failed to get borrow record. Error details: ' + err.message });
} else if (results.length === 0) {
res.status(404).json({ error: 'Borrow record not found' });
} else {
res.json(results[0]);
}
});
});
// 添加收藏路由
app.post('/user/add-favorite', (req, res) => {
const { userId, bookId } = req.body;
// 先检查该用户是否已经收藏了这本书
const checkFavoriteQuery = 'SELECT * FROM favorites WHERE user_id =? AND book_id =?';
db.query(checkFavoriteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error' });
} else if (results.length > 0) {
// 已收藏,提示用户
res.status(400).json({ error: 'This book has already been added to favorites' });
} else {
// 可以添加收藏,插入记录到 favorites 表
const insertFavoriteQuery = 'INSERT INTO favorites (user_id, book_id) VALUES (?,?)';
db.query(insertFavoriteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Failed to add to favorites' });
} else {
// 返回成功的 JSON 响应
res.status(200).json({ message: 'Book added to favorites successfully' });
}
});
}
});
});
// 删除收藏书籍路由
app.post('/user/delete-favorite', (req, res) => {
const { userId, bookId } = req.body;
const deleteQuery = 'DELETE FROM favorites WHERE user_id =? AND book_id =?';
db.query(deleteQuery, [userId, bookId], (err, results) => {
if (err) {
res.status(500).json({ error: 'Server error when deleting favorite' });
} else if (results.affectedRows === 0) {
// 如果受影响的行数为0,表示没有找到对应的收藏记录,即可能已经不存在该收藏了
res.status(400).json({ error: 'This book is not in your favorites' });
} else {
res.status(200).json({ message: 'Book removed from favorites successfully' });
}
});
});
// 从收藏中借阅书籍
app.post('/user/borrow-from-favorite', (req, res) => {
const { userId, bookId } = req.body;
// 先从收藏中删除这本书
const deleteFavoriteQuery = 'DELETE FROM favorites WHERE user_id = ? AND book_id = ?';
db.query(deleteFavoriteQuery, [userId, bookId], (err, deleteResults) => {
if (err) {
console.error('Error deleting favorite before borrowing:', err);
res.status(500).json({ error: 'Failed to borrow book from favorites' });
return;
}
if (deleteResults.affectedRows === 0) {
res.status(400).json({ error: 'This book is not in your favorites' });
return;
}
code Copy code
// 然后借阅这本书
const borrowQuery = 'INSERT INTO borrow_records (user_id, book_id, borrow_date) VALUES (?, ?, NOW())';
db.query(borrowQuery, [userId, bookId], (err, borrowResults) => {
if (err) {
console.error('Error borrowing book:', err);
res.status(500).json({ error: 'Failed to borrow book' });
} else {
// 返回成功的 JSON 响应
res.status(200).json({ message: 'Book borrowed from favorites successfully' });
}
});
});
// 监听端口
const PORT = 3000;
app.listen(PORT, () => {
console.log(Server running on port ${PORT});
}); 根据代码,修改删除图书模块,让他只能删除id改为按照书名删除
2. 修改后端代码 在后端,我们需要添加一个新的路由,处理通过书名删除图书的请求。
添加删除图书(通过书名)路由 javascript Copy code
// 删除图书通过书名
app.post('/admin/delete-book-by-title', (req, res) => {
const { title } = req.body; // 获取书名
// 确保书名是有效的字符串
if (!title || typeof title !== 'string') {
return res.status(400).json({ error: 'Invalid book title format' });
}
// SQL 查询使用书名删除图书
const query = 'DELETE FROM books WHERE title = ?';
db.query(query, [title], (err, results) => {
if (err) {
console.error('Error deleting book:', err);
return res.status(500).json({ error: 'Failed to delete book. Error details: ' + err.message });
} else {
if (results.affectedRows > 0) {
res.send('Book deleted');
} else {
res.status(404).send('No book found with that title');
}
}
});
});
3. 整体代码结构 确保前端的 JavaScript 中调用新的删除图书方法,并且后端增加路线来处理它。
4. 测试
运行 Node.js 服务器 :确保你的后端代码无误并能够正常启动。
在浏览器中打开管理员页面 :尝试使用书名来删除图书。
在数据库中 :确认你的书存在并且能够根据输入的书名删除。
通过这种方式,你将能够使用书名成功删除图书,与通过 ID 删除的方式完全分开。有任何问题,请随时告诉我。