server.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. // 导入Express框架
  2. const express = require('express');
  3. // 导入body-parser中间件,用于解析请求体中的JSON数据
  4. const bodyParser = require('body-parser');
  5. // 创建Express应用
  6. const app = express();
  7. // 定义端口号
  8. const PORT = 3000;
  9. // 使用body-parser中间件解析JSON格式的请求体
  10. app.use(bodyParser.json());
  11. // 定义登录凭据,实际开发中这些应存储在数据库中,并且密码应进行加密处理
  12. const users = {
  13. 'admin': 'password123' // 这里简单使用静态用户名和密码
  14. };
  15. // 创建登录路由处理POST请求
  16. app.post('/api/login', (req, res) => {
  17. const { username, password } = req.body; // 从请求体中解构用户名和密码
  18. // 验证用户名和密码是否匹配预设的凭据
  19. if (users[username] && users[username] === password) {
  20. // 如果匹配,返回登录成功的消息和状态码200
  21. res.status(200).send({ message: '登录成功' });
  22. } else {
  23. // 如果不匹配,返回错误消息和状态码401
  24. res.status(401).send({ message: '用户名或密码错误' });
  25. }
  26. });
  27. // 启动服务器,监听指定端口
  28. app.listen(PORT, () => {
  29. console.log(`服务器运行在 http://localhost:${PORT}`);
  30. });