feat: 初始化前端和后端项目
- 创建前端项目结构,包括 Vue 3、Uni-app 等相关配置 - 添加后端项目结构,使用 Express 和 TypeORM 连接数据库 - 实现基本的体重记录 CRUD 功能 - 配置项目相关文件,如 .gitignore、.npmrc 等
This commit is contained in:
51
server/app.js
Normal file
51
server/app.js
Normal file
@@ -0,0 +1,51 @@
|
||||
const express = require('express');
|
||||
const bodyParser = require('body-parser');
|
||||
const typeorm = require('typeorm');
|
||||
const app = express();
|
||||
const port = 3000;
|
||||
|
||||
// 引入 reflect-metadata,这是 TypeORM 的依赖
|
||||
require('reflect-metadata');
|
||||
|
||||
app.use(bodyParser.json());
|
||||
|
||||
// 连接到数据库
|
||||
typeorm.createConnection().then(connection => {
|
||||
console.log('数据库连接成功');
|
||||
|
||||
const weightRecordRepository = connection.getRepository('WeightRecord');
|
||||
|
||||
// 添加体重记录
|
||||
app.post('/api/weight', async (req, res) => {
|
||||
try {
|
||||
const { date, weight, unit } = req.body;
|
||||
const weightRecord = weightRecordRepository.create({ date, weight, unit });
|
||||
await weightRecordRepository.save(weightRecord);
|
||||
res.status(200).send('体重记录成功');
|
||||
} catch (error) {
|
||||
console.error('保存体重记录失败:', error);
|
||||
res.status(500).send('保存体重记录失败');
|
||||
}
|
||||
});
|
||||
|
||||
// 获取所有体重记录
|
||||
app.get('/api/weight', async (req, res) => {
|
||||
try {
|
||||
const weightRecords = await weightRecordRepository.find({
|
||||
order: {
|
||||
date: 'DESC'
|
||||
}
|
||||
});
|
||||
res.status(200).json(weightRecords);
|
||||
} catch (error) {
|
||||
console.error('获取体重记录失败:', error);
|
||||
res.status(500).send('获取体重记录失败');
|
||||
}
|
||||
});
|
||||
|
||||
app.listen(port, () => {
|
||||
console.log(`后端服务运行在 http://localhost:${port}`);
|
||||
});
|
||||
}).catch(error => {
|
||||
console.error('数据库连接失败:', error);
|
||||
});
|
||||
Reference in New Issue
Block a user