2user.html:375 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'ok')
at user.html:375:27
package com.example.librarysystem.controller;
//
import com.example.librarysystem.entity.BorrowRecord;
import com.example.librarysystem.mapper.BorrowRecordsMapper;
import com.example.librarysystem.service.BorrowRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/borrow-records")
public class BorrowRecordController {
@Autowired
private BorrowRecordService borrowRecordService;
@Autowired
private BorrowRecordsMapper borrowRecordsMapper;
code
@PostMapping("/borrow")
public ResponseEntity<?> borrowBook(@RequestBody BorrowRecord borrowRecord) {
try {
BorrowRecord savedRecord = borrowRecordService.borrowBook(borrowRecord);
return new ResponseEntity<>(savedRecord, HttpStatus.OK);
} catch (RuntimeException e) {
return new ResponseEntity<>("借阅图书失败:" + e.getMessage(), HttpStatus.CONFLICT);
} catch (Exception e) {
return new ResponseEntity<>("借阅图书失败:" + e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
@GetMapping("/user/borrow-history/{userId}")
public ResponseEntity<List<Map<String, Object>>> getBorrowHistoryByUserId(@PathVariable Long userId) {
List<Map<String, Object>> records = borrowRecordsMapper.findBorrowHistoryByUserId(userId);
System.out.println("Borrow history records: " + records);
return new ResponseEntity<>(records, HttpStatus.OK);
}
@GetMapping("/all") // 通过 /api/borrow-records/all 获取所有借阅记录
public ResponseEntity<List<Map<String, Object>>> getAllBorrowRecords() {
List<Map<String, Object>> records = borrowRecordService.getAllBorrowRecords();
return new ResponseEntity<>(records, HttpStatus.OK);
}
@GetMapping()
public ResponseEntity<List<BorrowRecord>> getBorrowRecords() {
List<BorrowRecord> records = borrowRecordService.getBorrowRecords();
return new ResponseEntity<>(records, HttpStatus.OK);
}
@PostMapping("/return/{id}")
public ResponseEntity<String> returnBook(@PathVariable Long id) {
try {
borrowRecordService.returnBook(id);
return new ResponseEntity<>("还书成功", HttpStatus.OK); // 直接返回字符串
} catch (Exception e) {
return new ResponseEntity<>("还书失败: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping("/{id}")
public ResponseEntity<BorrowRecord> getBorrowRecordById(@PathVariable Long id) {
BorrowRecord record = borrowRecordService.getBorrowRecordById(id);
if (record!= null) {
return new ResponseEntity<>(record, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}package com.example.librarysystem.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.librarysystem.entity.BorrowRecord;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
/**
-
-
Mapper 接口
-
-
@author xxx
-
@since 2024-12-23
*/
@Mapper
public interface BorrowRecordsMapper extends BaseMapper {
@Select("SELECT br.id, u.username, b.title, b.author, br.borrow_date, br.return_date, br.is_returned " +
"FROM borrow_records br " +
"JOIN books b ON br.book_id = b.id " +
"JOIN users u ON br.user_id = u.id")
List<Map<String, Object>> findAllBorrowRecords();
code
// 添加此方法
@Select("SELECT br.id, u.username, b.title, b.author, br.borrow_date, br.return_date, br.is_returned " +
"FROM borrow_records br " +
"JOIN books b ON br.book_id = b.id " +
"JOIN users u ON br.user_id = u.id " +
"WHERE br.user_id = #{userId}")
List<Map<String, Object>> findBorrowHistoryByUserId(Long userId);
}
package com.example.librarysystem.service;
//
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.librarysystem.entity.BorrowRecord;
import com.example.librarysystem.mapper.BorrowRecordsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
@Service
public class BorrowRecordService {
@Autowired
private BorrowRecordsMapper borrowRecordMapper;
code
public BorrowRecord borrowBook(BorrowRecord borrowRecord) {
// 检查用户是否已借阅同样的书籍
List<BorrowRecord> existingRecords = borrowRecordMapper.selectList(
Wrappers.<BorrowRecord>lambdaQuery()
.eq(BorrowRecord::getUserId, borrowRecord.getUserId())
.eq(BorrowRecord::getBookId, borrowRecord.getBookId()));
// 如果已有记录,则无法借阅同一本书
if (!existingRecords.isEmpty()) {
throw new RuntimeException("用户已借阅该书,无法重新借阅");
}
if (borrowRecord.getBorrowDate() == null) {
borrowRecord.setBorrowDate(LocalDateTime.now()); // 设置当前时间为借阅时间
}
borrowRecordMapper.insert(borrowRecord);
return borrowRecord;
}
public List<BorrowRecord> getBorrowRecordsByUserId(Long userId) {
return borrowRecordMapper.selectList(
Wrappers.<BorrowRecord>lambdaQuery().eq(BorrowRecord::getUserId, userId)
);
}
public void returnBook(Long recordId) {
BorrowRecord record = borrowRecordMapper.selectById(recordId);
if (record == null) {
throw new RuntimeException("未找到借阅记录");
}
record.setIsReturned(true);
record.setReturnDate(LocalDateTime.now().toString()); // 或者可以根据需要设定返回日期格式
borrowRecordMapper.updateById(record);
}
public List<BorrowRecord> getBorrowRecords() {
return borrowRecordMapper.selectList(null);
}
public BorrowRecord getBorrowRecordById(Long id) {
return borrowRecordMapper.selectById(id);
}
public List<Map<String, Object>> getAllBorrowRecords() {
return borrowRecordMapper.findAllBorrowRecords();
}
public void deleteBorrowRecord(Long id) {
borrowRecordMapper.deleteById(id);
}
public BorrowRecord editBorrowRecord(BorrowRecord borrowRecord) {
borrowRecordMapper.updateById(borrowRecord);
return borrowRecord;
}
}
code
<script>
document.addEventListener("DOMContentLoaded", function () {
updateUsernameDisplay();
});
function logout() {
alert('已退出登录');
localStorage.removeItem('userInfo');
localStorage.removeItem('username');
updateUsernameDisplay();
window.location.href = 'login.html';
}
function updateUsernameDisplay() {
const username = localStorage.getItem('username');
const usernameDisplay = document.getElementById('username-display');
if (username) {
usernameDisplay.textContent = username;
} else {
usernameDisplay.textContent = '未登录';
console.log('在 localStorage 中未找到用户名');
}
}
function showSection(section) {
const sections = document.querySelectorAll('.section');
sections.forEach(s => s.style.display = 'none');
document.getElementById(section + 'Section').style.display = 'block';
if (section === 'favorites') {
loadFavorites();
} else if (section === 'history') {
loadBorrowHistory();
}
}
function searchBooks() {
const keyword = document.getElementById('searchInput').value.trim();
if (keyword === '') {
alert('请输入搜索关键词');
return;
}
// 移除特殊字符
const sanitizedKeyword = keyword.replace(/[%_]/g, '');
fetch('http://localhost:8080/api/books/search', {
method: 'POST',
headers: {
'Content-Type': 'application/json' // 声明使用 JSON 格式
},
body: JSON.stringify({ keyword }) // 将关键词封装成 JSON 发送到后端
})
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json(); // 解析 JSON 数据
})
.then(data => {
displaySearchResults(data); // 将结果显示在页面上
})
.catch(error => console.error('Error:', error)); // 处理异常情况
}
function displaySearchResults(books) {
const searchResults = document.getElementById('searchResults');
searchResults.innerHTML = ''; // 清空之前的结果
code
// 检查返回的书籍列表是否为空
if (books.length === 0) {
searchResults.innerHTML = '<p>没有找到相关书籍</p>'; // 提示用户未找到书籍
} else {
books.forEach(book => {
const listItem = document.createElement('div');
listItem.className = 'search-result-item';
listItem.innerHTML = `
<div>
<strong>书名:</strong> ${book.title}<br>
<strong>作者:</strong> ${book.author}<br>
<strong>出版年份:</strong> ${book.yearPublished || '未知'}
</div>
<div class="book-actions">
<button onclick="borrowBook(${book.id})">借阅</button>
<button onclick="addToFavorites(${book.id})">添加到收藏</button>
</div>
`;
searchResults.appendChild(listItem); // 将书籍信息添加到显示区域
});
}
}
function getUserId() {
const userInfo = JSON.parse(localStorage.getItem('userInfo'));
return userInfo ? userInfo.id : null;
}
function checkBorrowHistory(userId) {
return fetch(http://localhost:8080/api/borrow-records/user/borrow-history/${userId})
.then(response => {
if (!response.ok) {
throw new Error('未找到借阅记录');
}
return response.json();
})
.catch(error => {
console.error('Error fetching borrow history:', error);
alert('获取借阅历史时发生了错误,请稍后再试');
return []; // 返回空数组,以避免未定义错误
});
}
// 借阅书籍
function borrowBook(bookId) {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
code
// 查询借阅历史
checkBorrowHistory(userId)
.then(borrowRecords => {
if (borrowRecords.length > 0) {
alert('您已经有借阅记录,无法借阅新的书籍!');
return; // 不再继续借阅
}
return fetch('http://localhost:8080/api/borrow-records/borrow', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
userId: userId,
bookId: bookId,
borrowDate: new Date().toISOString() // 添加借阅日期
})
});
})
.then(response => {
if (!response.ok) {
// 捕抓并处理响应中的错误
throw new Error('借阅请求未发送');
}
return response.json();
})
.then(data => {
alert('您已成功借阅');
loadBorrowHistory(); // 更新借阅历史显示
})
}
code
// 加载借阅历史
function loadBorrowHistory() {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
// 更新 API 路径
fetch(`http://localhost:8080/api/borrow-records/user/borrow-history/${userId}`)
.then(response => {
if (!response.ok) {
throw new Error('未找到借阅记录');
}
return response.json();
})
.then(data => {
displayBorrowHistory(data);
})
.catch(error => {
console.error('Error:', error);
alert('加载借阅历史时发生错误,请稍后再试');
});
}
function displayBorrowHistory(borrowRecords) {
const borrowHistory = document.getElementById('borrowHistory');
borrowHistory.innerHTML = '';
code
if (borrowRecords.length === 0) {
borrowHistory.innerHTML = '<p>没有借阅记录</p>';
} else {
borrowRecords.forEach(record => {
const listItem = document.createElement('li');
const borrowDate = new Date(record.borrow_date || Date.now()); // 若 borrow_date 为 null, 使用当前时间
const formattedDate = borrowDate.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
});
listItem.textContent = `书名: ${record.title || '未知'} - 作者: ${record.author || '未知'} - 借阅日期: ${formattedDate} - 状态: ${record.is_returned ? '已还书' : '未还书'}`;
const returnButton = document.createElement('button');
returnButton.textContent = '还书';
returnButton.onclick = function () {
console.log('Attempting to return book with Record ID:', record.id);
returnBook(record.id, returnButton);
};
if (record.is_returned) {
returnButton.disabled = true;
returnButton.textContent = '已还书';
}
code
listItem.appendChild(returnButton);
borrowHistory.appendChild(listItem);
});
}
}
function returnBook(borrowRecordId, returnButton) {
const userId = getUserId();
if (!userId || !borrowRecordId) {
alert('无效的用户 ID 或借阅记录 ID');
return;
}
code
returnButton.disabled = true;
returnButton.textContent = '处理中...';
fetch(`http://localhost:8080/api/borrow-records/return/${borrowRecordId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
return response.text(); // 使用 .text() 解析文本响应
})
.then(data => {
console.log(data)
alert(data); // data 是字符串格式的消息
loadBorrowHistory(); // 重新加载借阅历史
})
.catch(error => {
console.error('Error:', error);
alert('还书时发生错误,请稍后再试');
returnButton.disabled = false;
returnButton.textContent = '还书'; // 恢复按钮状态
});
}
code
// 添加到收藏
function addToFavorites(bookId) {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
fetch('http://localhost:8080/api/favorites/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ userId: userId, bookId: bookId }) // 确保这两个值非空
})
.then(response => {
if (!response.ok) {
return response.text().then(text => {
throw new Error('添加收藏时发生错误:' + text);
});
}
return response.json();
})
.then(data => {
alert('已成功添加到收藏!');
loadFavorites(); // 重新加载收藏列表
})
.catch(error => {
console.error('Error:', error);
alert('添加收藏时发生错误,请稍后再试');
});
}
code
// 加载收藏书籍
function loadFavorites() {
const userId = getUserId();
console.log('加载收藏的用户ID:', userId); // 增加调试信息
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
fetch(`http://localhost:8080/api/favorites/${userId}`)
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(data => {
displayFavorites(data); // 确保数据结构正确
})
.catch(error => {
console.error('Error:', error);
alert('加载收藏时发生错误,请稍后再试');
});
}
code
// 显示收藏书籍
function displayFavorites(favoriteBooks) {
const favoritesList = document.getElementById('favoritesList');
favoritesList.innerHTML = '';
if (favoriteBooks.length === 0) {
favoritesList.innerHTML = '<p>没有收藏的书籍</p>';
} else {
const userId = getUserId(); // 获取用户 ID
checkBorrowHistory(userId)
.then(borrowRecords => {
const hasBorrowed = borrowRecords.length > 0; // 检查是否有借阅记录
favoriteBooks.forEach(favorite => {
const listItem = document.createElement('li');
listItem.innerHTML = `书名: ${favorite.bookTitle} - 作者: ${favorite.bookAuthor}`;
const borrowButton = document.createElement('button');
borrowButton.textContent = hasBorrowed ? '借阅' : '借阅';
borrowButton.disabled = hasBorrowed; // 如果有借阅记录,禁用借阅按钮
borrowButton.onclick = function () {
borrowFromFavorites(favorite.bookId);
};
const deleteButton = document.createElement('button');
deleteButton.textContent = '删除收藏';
deleteButton.onclick = function () {
removeFromFavorites(favorite.bookId);
};
listItem.appendChild(borrowButton);
listItem.appendChild(deleteButton);
favoritesList.appendChild(listItem);
});
})
.catch(error => {
console.error('Error:', error);
alert('加载收藏时发生错误,请稍后再试');
});
}
}
// 从收藏中借阅书籍
function borrowFromFavorites(bookId) {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
code
// 检查借阅历史
checkBorrowHistory(userId)
.then(borrowRecords => {
if (borrowRecords.length > 0) {
alert('您已借阅记录,无法借阅新的书籍!');
return;
}
return fetch('http://localhost:8080/api/borrow-records/borrow', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ userId: userId, bookId: bookId })
});
})
.then(response => {
if (!response.ok) {
throw new Error('借阅失败,未能与服务器连接');
}
return response.json();
})
.then(data => {
alert('借阅成功!');
loadFavorites();
loadBorrowHistory();
})
.catch(error => {
console.error('Error:', error);
alert('借阅时发生错误,请稍后再试');
});
}
// 从收藏中删除书籍
function removeFromFavorites(bookId) {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
code
fetch(`http://localhost:8080/api/favorites/remove/${userId}/${bookId}`, {
method: 'DELETE', // 使用 DELETE 方法
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
if (!response.ok) {
return response.text().then(text => {
throw new Error('删除失败:' + text);
});
}
return response.text(); // 获取成功信息
})
.then(data => {
alert(data); // 提示成功
loadFavorites(); // 重新加载收藏列表
})
.catch(error => {
console.error('Error:', error);
alert('删除收藏时发生错误,请稍后再试');
});
}
</script>
code
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteBorrowRecord(@PathVariable Long id) {
borrowRecordService.deleteBorrowRecord(id);
return new ResponseEntity<>("Borrow record deleted successfully", HttpStatus.OK);
}
@PostMapping("/edit")
public ResponseEntity<?> editBorrowRecord(@RequestBody BorrowRecord borrowRecord) {
BorrowRecord editedRecord = borrowRecordService.editBorrowRecord(borrowRecord);
return new ResponseEntity<>(editedRecord, HttpStatus.OK);
}
}