server.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. const express = require('express');
  2. const fs = require('fs');
  3. const path = require('path');
  4. const bcrypt = require('bcrypt');
  5. const bodyParser = require('body-parser');
  6. const app = express();
  7. const PORT = 3000;
  8. const USER_FILE = path.join(__dirname, 'user.json');
  9. // 中间件
  10. app.use(bodyParser.json());
  11. // 初始化用户文件(如果不存在)
  12. if (!fs.existsSync(USER_FILE)) {
  13. fs.writeFileSync(USER_FILE, JSON.stringify([], null, 2));
  14. }
  15. // 读取用户数据
  16. function readUsers() {
  17. try {
  18. const data = fs.readFileSync(USER_FILE, 'utf8');
  19. return JSON.parse(data);
  20. } catch (err) {
  21. console.error('Error reading user file:', err);
  22. return [];
  23. }
  24. }
  25. // 写入用户数据
  26. function writeUsers(users) {
  27. try {
  28. fs.writeFileSync(USER_FILE, JSON.stringify(users, null, 2));
  29. } catch (err) {
  30. console.error('Error writing user file:', err);
  31. }
  32. }
  33. // 文档路由
  34. app.get("/device", (req, res) => {
  35. /**
  36. 这个JSON结构包含了以下主要信息:
  37. 设备基本信息(ID、类型、制造商等)
  38. 时间戳(ISO 8601格式)
  39. 定位信息(经纬度、高度、精度、速度和方向)
  40. 电池状态(电量、电压、充电状态和剩余续航)
  41. 车辆状态(点火状态、锁定状态等)
  42. 环境数据(温度和湿度)
  43. 遥测数据(里程、总运行时间、信号强度)
  44. 附加数据(GPS定位类型、可见卫星数等)
  45. 您可以根据实际需求调整字段或添加更多信息。
  46. */
  47. res.json({
  48. "device": {
  49. "id": "EBike-123456789",
  50. "type": "electric_bike",
  51. "manufacturer": "ExampleTech",
  52. "model": "ET-3000",
  53. "firmware_version": "1.2.3"
  54. },
  55. "timestamp": "2023-05-16T14:30:45Z",
  56. "location": {
  57. "latitude": 39.9042,
  58. "longitude": 116.4074,
  59. "altitude": 45.2,
  60. "accuracy": 5.0,
  61. "speed": 25.5,
  62. "heading": 180.0
  63. },
  64. "battery": {
  65. "level": 78.5,
  66. "voltage": 48.2,
  67. "charging": false,
  68. "remaining_range": 65.2
  69. },
  70. "status": {
  71. "ignition": true,
  72. "locked": false,
  73. "alarm_triggered": false,
  74. "maintenance_required": false
  75. },
  76. "environment": {
  77. "temperature": 28.5,
  78. "humidity": 45.0
  79. },
  80. "telemetry": {
  81. "odometer": 1250.3,
  82. "total_runtime": 3568,
  83. "signal_strength": 85
  84. },
  85. "additional_data": {
  86. "gps_fix_type": "3D",
  87. "satellites_in_view": 12,
  88. "cellular_network": "5G",
  89. "timestamp_device": "2023-05-16T14:30:45Z"
  90. }
  91. })
  92. })
  93. // API文档路由
  94. app.get('/', (req, res) => {
  95. const apiDocs = {
  96. description: '用户认证服务API文档',
  97. endpoints: [
  98. {
  99. method: 'POST',
  100. path: '/signup',
  101. description: '用户注册',
  102. requestBody: {
  103. username: 'string (必需)',
  104. password: 'string (必需)'
  105. },
  106. responses: {
  107. '201': '用户创建成功',
  108. '400': '用户名已存在或缺少用户名/密码'
  109. }
  110. },
  111. {
  112. method: 'POST',
  113. path: '/login',
  114. description: '用户登录',
  115. requestBody: {
  116. username: 'string (必需)',
  117. password: 'string (必需)'
  118. },
  119. responses: {
  120. '200': '登录成功',
  121. '400': '缺少用户名/密码',
  122. '401': '无效的用户名或密码'
  123. }
  124. }
  125. ],
  126. note: '所有密码都会经过哈希处理后再存储'
  127. };
  128. res.json(apiDocs);
  129. });
  130. app.get("/test", (req, res) => {
  131. let style = `
  132. h1{
  133. color:red;
  134. }
  135. `
  136. let template = `<h1>这里是测试页面</h1>`
  137. res.write(`<!DOCTYPE html>
  138. <html lang="zh">
  139. <head>
  140. <meta charset="UTF-8">
  141. <title>TEST UTF-8编码示例</title>
  142. <style>${style}</style>
  143. </head>
  144. <body>
  145. ${template}
  146. </body>
  147. </html>`)
  148. })
  149. // 注册路由
  150. app.post('/signup', async (req, res) => {
  151. const { username, password } = req.body;
  152. if (!username || !password) {
  153. return res.status(400).json({ error: 'Username and password are required' });
  154. }
  155. const users = readUsers();
  156. // 检查用户是否已存在
  157. if (users.some(user => user.username === username)) {
  158. return res.status(400).json({ error: 'Username already exists' });
  159. }
  160. // 哈希密码
  161. const hashedPassword = await bcrypt.hash(password, 10);
  162. // 添加新用户
  163. users.push({
  164. username,
  165. password: hashedPassword
  166. });
  167. writeUsers(users);
  168. res.status(201).json({ message: 'User created successfully' });
  169. });
  170. // 登录路由
  171. app.post('/login', async (req, res) => {
  172. const { username, password } = req.body;
  173. if (!username || !password) {
  174. return res.status(400).json({ error: 'Username and password are required' });
  175. }
  176. const users = readUsers();
  177. const user = users.find(user => user.username === username);
  178. if (!user) {
  179. return res.status(401).json({ error: 'Invalid username or password' });
  180. }
  181. // 验证密码
  182. const passwordMatch = await bcrypt.compare(password, user.password);
  183. if (!passwordMatch) {
  184. return res.status(401).json({ error: 'Invalid username or password' });
  185. }
  186. res.json({ message: 'Login successful' });
  187. });
  188. // 启动服务器
  189. app.listen(PORT, () => {
  190. console.log(`Server is running on http://localhost:${PORT}`);
  191. });