12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- /*
- * @Author: 危齐晟 1913361097@qq.com
- * @Date: 2024-12-17 10:31:46
- * @LastEditors: 危齐晟 1913361097@qq.com
- * @LastEditTime: 2024-12-17 15:24:58
- * @FilePath: \202226701045\poem-life-serve\db\dbServe.js
- * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
- */
- // server.js
- const express = require('express');
- const mysql = require('mysql2');
- const cors = require('cors');
- const app = express();
- const PORT = 3000;
- // CORS 设置
- app.use(cors());
- app.use(express.json());
- // MySQL 连接设置
- const db = mysql.createConnection({
- host: 'localhost',
- user: 'root', // 替换为您的MySQL用户名
- password: '123456', // 替换为您的MySQL密码
- database: 'poemLifeApp',
- ssl: false // 禁用SSL连接(如果不需要的话)
- });
- // 连接到数据库
- db.connect(err => {
- if (err) {
- console.error('Database connection failed: ' + err.stack);
- return;
- }
- console.log('Connected to database.');
- });
- // 获取书籍列表的 API
- app.get('/api/books', (req, res) => {
- db.query('SELECT * FROM books', (err, results) => {
- if (err) {
- return res.status(500).json({ error: err });
- }
- res.json(results);
- });
- });
- app.get('/api/poems/:bookId', (req, res) => {
- const bookId = req.params.bookId;
- const query = 'SELECT * FROM poems WHERE book_id = ?';
- db.query(query, [bookId], (err, results) => {
- if (err) return res.status(500).json({ error: err });
- res.json(results);
- });
- });
- app.get('/api/poem-contents/:poemId', (req, res) => {
- const poemId = req.params.poemId;
- const query = 'SELECT content FROM poem_contents WHERE poem_id = ?';
- db.query(query, [poemId], (err, results) => {
- if (err) return res.status(500).json({ error: err });
- if (results.length === 0) return res.status(404).json({ message: 'Content not found' });
- res.json(results[0]);
- });
- });
- app.get('/api/categories', (req, res) => {
- const categories = ['书籍', '选集', '主题', '写景', '节日', '节气', '词牌', '时间', '时令', '花卉', '课本', '地理', '城市', '名山', '用典'];
- res.json(categories);
- });
- app.get('/api/books', (req, res) => {
- const books = [
- { id: 1, title: '唐诗全集', category: '书籍', count: 200 },
- { id: 2, title: '诗经全集', category: '选集', count: 305 },
- { id: 3, title: '楚辞全集', category: '选集', count: 17 },
- { id: 4, title: '道德经', category: '选集', count: 81 },
- { id: 5, title: '时间简史', category: '主题', count: 150 },
- // 其他书籍...
- ];
- res.json(books);
- });
-
- // 启动服务器
- app.listen(PORT, () => {
- console.log(`Server is running on http://localhost:${PORT}`);
- });
|