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