Files
kuafu-health-manage/server/app.js
Kubbo 47306782a8 feat: 初始化前端和后端项目
- 创建前端项目结构,包括 Vue 3、Uni-app 等相关配置
- 添加后端项目结构,使用 Express 和 TypeORM 连接数据库
- 实现基本的体重记录 CRUD 功能
- 配置项目相关文件,如 .gitignore、.npmrc 等
2025-04-19 19:31:33 +08:00

52 lines
1.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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);
});