node.js实现登录注册
时间: 2023-07-28 13:07:55 浏览: 42
好的,下面是一个简单的 Node.js 实现登录注册的示例代码:
首先,需要引入 Express 和 body-parser 模块:
```javascript
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
```
然后,定义一个数组 users 来存储用户信息:
```javascript
const users = [];
```
接下来,实现注册功能:
```javascript
app.post('/register', (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ message: '用户名或密码不能为空' });
}
const user = users.find(u => u.username === username);
if (user) {
return res.status(400).json({ message: '用户名已存在' });
}
const newUser = { username, password };
users.push(newUser);
res.status(201).json({ message: '注册成功' });
});
```
这段代码首先从请求体中获取用户名和密码,然后判断是否为空。接着,在 users 数组中查找是否已经存在该用户名,如果存在,则返回错误信息。最后,将新用户信息添加到 users 数组中,并返回注册成功的信息。
接下来,实现登录功能:
```javascript
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ message: '用户名或密码不能为空' });
}
const user = users.find(u => u.username === username && u.password === password);
if (!user) {
return res.status(401).json({ message: '用户名或密码错误' });
}
res.json({ message: '登录成功' });
});
```
这段代码与注册功能类似,首先从请求体中获取用户名和密码,然后判断是否为空。接着,在 users 数组中查找是否存在该用户名和密码,如果不存在,则返回错误信息。最后,返回登录成功的信息。
完整的代码如下:
```javascript
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const users = [];
app.post('/register', (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ message: '用户名或密码不能为空' });
}
const user = users.find(u => u.username === username);
if (user) {
return res.status(400).json({ message: '用户名已存在' });
}
const newUser = { username, password };
users.push(newUser);
res.status(201).json({ message: '注册成功' });
});
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ message: '用户名或密码不能为空' });
}
const user = users.find(u => u.username === username && u.password === password);
if (!user) {
return res.status(401).json({ message: '用户名或密码错误' });
}
res.json({ message: '登录成功' });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
```
希望这个示例代码对你有帮助!