使用express框架实现登录和注册功能 get : login -> 渲染登录表单页面 get : register -> 渲染注册表单页面 你 post : login -> 接收表单传递过来的用户名和密码 判断是否登录成功 用户名是否为空 密码名是否为空 post : register -> 接收表单传递过来的用户名和密码 persons.json中有无此用户,如果有返回 已注册。如果没有则注册成功, 注意:用户信息多了一个注册时间time(中间件) [ {"username":"admin","password":"123","time":"2021年04月24日 09:52:21"} ]
时间: 2023-06-16 17:04:19 浏览: 29
好的,我可以给你一个实现登录和注册功能的代码示例:
```
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const moment = require('moment');
const app = express();
// 设置中间件,解析POST请求的body
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// 登录页面
app.get('/login', (req, res) => {
res.send(`
<form action="/login" method="post">
<input type="text" name="username" placeholder="用户名">
<input type="password" name="password" placeholder="密码">
<button type="submit">登录</button>
</form>
`);
});
// 注册页面
app.get('/register', (req, res) => {
res.send(`
<form action="/register" method="post">
<input type="text" name="username" placeholder="用户名">
<input type="password" name="password" placeholder="密码">
<button type="submit">注册</button>
</form>
`);
});
// 登录接口
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
res.send('用户名和密码不能为空');
return;
}
// 读取用户信息
const users = JSON.parse(fs.readFileSync('persons.json'));
const user = users.find(u => u.username === username && u.password === password);
if (user) {
res.send(`欢迎登录,${username}`);
} else {
res.send('用户名或密码错误');
}
});
// 注册接口
app.post('/register', (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
res.send('用户名和密码不能为空');
return;
}
// 读取用户信息
const users = JSON.parse(fs.readFileSync('persons.json'));
if (users.find(u => u.username === username)) {
res.send('用户名已存在');
return;
}
// 注册用户
const newUser = {
username,
password,
time: moment().format('YYYY年MM月DD日 HH:mm:ss')
};
users.push(newUser);
fs.writeFileSync('persons.json', JSON.stringify(users));
res.send(`注册成功,欢迎加入,${username}`);
});
app.listen(3000, () => console.log('Server is running on http://localhost:3000'));
```
这个代码示例使用了Express框架,同时使用了`body-parser`解析POST请求的body,以及`fs`模块读写文件。其中,登录页面和注册页面使用了简单的HTML表单,分别发送POST请求到`/login`和`/register`接口。在接口中,我们读取了`persons.json`文件中的用户信息,根据用户名和密码判断用户是否存在或登录成功,如果是注册接口,则判断用户名是否已存在,如果不存在则将新用户信息写入到`persons.json`文件中。另外,我们还使用了`moment`模块获取当前时间,将其作为用户信息中的注册时间。