node.js写登录注册接口
时间: 2023-08-10 13:12:00 浏览: 47
好的,下面是一个简单的登录注册接口示例,使用 Node.js 和 Express 框架:
```javascript
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const { check, validationResult } = require('express-validator/check');
// 设置 body-parser 中间件
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// 定义用户数据
let users = [
{ id: 1, name: 'Alice', email: 'alice@example.com', password: '123456' },
{ id: 2, name: 'Bob', email: 'bob@example.com', password: 'abc123' }
];
// 注册接口
app.post('/register', [
// 验证表单字段
check('name').isLength({ min: 3 }).withMessage('姓名长度至少为 3 个字符'),
check('email').isEmail().withMessage('请输入有效的邮箱地址'),
check('password').isLength({ min: 6 }).withMessage('密码长度至少为 6 个字符')
], (req, res) => {
// 处理验证结果
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
// 检查邮箱是否已被注册
const userExists = users.some(user => user.email === req.body.email);
if (userExists) {
return res.status(400).json({ error: '该邮箱已被注册' });
}
// 创建新用户
const { name, email, password } = req.body;
const newUser = { id: Date.now(), name, email, password };
users.push(newUser);
res.json({ message: '注册成功', user: newUser });
});
// 登录接口
app.post('/login', (req, res) => {
const { email, password } = req.body;
// 查找用户
const user = users.find(user => user.email === email && user.password === password);
if (!user) {
return res.status(401).json({ error: '邮箱或密码错误' });
}
res.json({ message: '登录成功', user });
});
// 启动服务
app.listen(3000, () => {
console.log('Server started on port 3000');
});
```
以上代码中注册接口使用了 express-validator 来验证表单字段,登录接口则直接查找用户并判断账号密码是否正确。注意,这只是一个简单的示例,实际生产环境需要更加严格的数据验证和安全措施。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)