parent
c301ad068f
commit
a8de6adf91
@ -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}`);
|
||||
});
|
Loading…
Reference in new issue