From a8de6adf91c03f005b493f09593a2fd9c6554321 Mon Sep 17 00:00:00 2001 From: pzrxqba79 <1994211138@qq.com> Date: Fri, 11 Oct 2024 14:10:37 +0800 Subject: [PATCH] sr.py --- sr.py | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 sr.py diff --git a/sr.py b/sr.py new file mode 100644 index 0000000..9151ad2 --- /dev/null +++ b/sr.py @@ -0,0 +1,53 @@ +const express = require('express'); +const cors = require('cors'); +const bodyParser = require('body-parser'); +const bcrypt = require('bcrypt'); +const { body, validationResult } = require('express-validator'); +const morgan = require('morgan'); +const timeout = require('connect-timeout'); +const app = express(); +const PORT = 3000; +app.use(cors({ + origin: 'http://your-frontend-domain.com', + methods: ['GET', 'POST'], + allowedHeaders: ['Content-Type'] +})); +app.use(bodyParser.json()); +app.use(morgan('combined')); +app.use(timeout('5s')); + +let users = []; // 应该替换为实际的数据库 +app.post('/api/register', [ + body('username').notEmpty().withMessage('用户名不能为空'), + body('password').notEmpty().withMessage('密码不能为空'), + body('confirm_password').custom((value, { req }) => { + if (value !== req.body.password) { + throw new Error('密码不匹配'); + } + return true; + }) + +], async (req, res) => { + const errors = validationResult(req); + if (!errors.isEmpty()) { + return res.status(400).json({ errors: errors.array() }); + } + + const { username, password } = req.body; + const existingUser = users.find(user => user.username === username); + if (existingUser) { + return res.status(400).send('用户名已被注册'); + } + + const hashedPassword = await bcrypt.hash(password, 10); + users.push({ username, password: hashedPassword }); + res.status(201).send('注册成功'); +}); + +app.use((err, req, res, next) => { + console.error(err.stack); + res.status(500).send('服务器内部错误'); +}); +app.listen(PORT, () => { + console.log(`Server is running on http://localhost:${PORT}`); +}); \ No newline at end of file