You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.7 KiB

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