注册接口,用户提供必要的注册信息(如用户名和密码),服务器对用户进行验证并创建用户账号
- // 注册接口
- app.post('/register', async (req, res) => {
- try {
- const { username, email, password } = req.body;
-
- // 检查用户名和邮箱是否已被注册
- if (users.some(user => user.username === username)) {
- return res.status(400).json({ error: '用户名已被注册' });
- }
-
- if (users.some(user => user.email === email)) {
- return res.status(400).json({ error: '邮箱已被注册' });
- }
-
- // 使用bcrypt对密码进行哈希处理
- const hashedPassword = await bcrypt.hash(password, 10);
-
- // 创建新用户对象
- const user = {
- id: Date.now().toString(),
- username,
- email,
- password: hashedPassword
- };
-
- // 将用户信息存储到数据库
- users.push(user);
-
- // 创建访问令牌
- const token = jwt.sign({ userId: user.id }, 'secretKey');
-
- res.status(201).json({ message: '注册成功', token });
- } catch (error) {
- res.status(500).json({ error: '注册失败' });
- }
- });
登录接口,用户提供登录凭据(如用户名和密码),服务器验证凭据的正确性并颁发访问令牌
- app.post('/login', (req, res) => {
- // 获取登录凭据
- const { username, password } = req.body;
- // 在此处进行用户名和密码的验证,如检查用户名是否存在、密码是否匹配等;验证成功,颁发访问令牌;
- const token = createAccessToken(username);
-
- // 将访问令牌写入 Cookie
- res.cookie('token', token, {
- httpOnly: true,
- secure: true, // 仅在 HTTPS 连接时发送 Cookie
- sameSite: 'Strict' // 限制跨站点访问,提高安全性
- });
-
- // 返回登录成功的响应
- res.status(200).json({ message: '登录成功' });
- });
校验登录状态,服务器将校验请求中的登录凭据(Cookie 或访问令牌)的有效性
- app.get('/protected', (req, res) => {
- // 从请求的 Cookie 中提取访问令牌
- const token = req.cookies.token;
- // 或从请求头部中提取访问令牌,如果采用前端存储和发送访问令牌方式;示例代码,需根据实际情况进行解析 const token = req.headers.authorization.split(' ')[1];
-
- // 检查访问令牌的有效性
- if (!token) {
- return res.status(401).json({ error: '未提供访问令牌' });
- }
-
- try {
- // 验证访问令牌
- const decoded = verifyAccessToken(token);
-
- // 在此处进行更详细的用户权限校验等操作
-
- // 返回受保护资源
- res.status(200).json({ message: '访问受保护资源成功' });
- } catch (error) {
- res.status(401).json({ error: '无效的访问令牌' });
- }
- });
- // 从存储中获取访问令牌
- const token = localStorage.getItem('token');
-
- // 设置请求头部
- const headers = {
- 'Authorization': `Bearer ${token}`
- };
-
- // 发送请求时,手动设置请求头部
- fetch('/protected', { headers });
使用前端的 localStorage 来存储访问令牌,并在发送请求时手动设置了请求头部的 Authorization 字段。
注意:无论使用哪种方式,都需要在服务器端进行访问令牌的验证和安全性检查,以确保请求的合法性和保护用户数据的安全。