小菜鸟变大笨鸟使用nodecookie完成自动登录

51次阅读

共计 3553 个字符,预计需要花费 9 分钟才能阅读完成。

node,cookie 完成自动登录

注意点:
1 种一个 cookie,res.cookie(“cookie 名 ”,”cookie 内容 ”,{path: 路径,signed: 是否加密,maxAge: 超时时间})
2 cookie 加密,req.secret 规定一个加密规则,然后 res.cookie(“cookie 名 ”,”cookie 内容 ”,{path: 路径,signed:true,maxAge: 超时时间})
3 获取 cookie, 利用 cookie-parser, 先声明 server.use(cookieParser()); 获取,req.cookies;
4 cookie 解密:server.use(cookieParser(“asdfghjklpoiuytrewqasdgh1234567”)); 在使用 cookieparser 中间件的时候,告诉 cookieparse 你的加密规则, 然后使用 req.signedCookies

步骤:
1 安装 express express-static cookie-parser
2 引入 express express-static cookie-parser,创建一个 sever 并监听端口

代码:
html:


  <body>
    <div class="box">
      <p><span> 用户名:</span><input type="text" id="user"></p>
      <p><span> 密码:</span><input type="text" id="pass"></p>
      <p>
        <input type="checkbox" id="remberPassword"> 记住密码
      </p>
      <p><input type="button" id="login" value="登录"><input type="button" id="register" value="注册"></p>
    </div>
  </body>

css:

<style>
      .box {
        position: absolute;
        left: 0;
        right: 0;
        top: -800px;
        bottom: 0;
        margin: auto;
        transition: all ease 1s;
        width: 400px;
        height: 400px;
        border: 1px solid rgba(0, 0, 0, .5);
        box-shadow: 1px 1px 6px 2px rgba(0, 0, 0, .5);
      }
    </style>

js:

    $(document).ready(() => {setTimeout(() => {$(".box").css("top", "0");
      }, 15)

      // cookie 自动登录
      setTimeout(() => {
        ajax({
          url: "http://localhost:8020/auto",
          type: "get",
          success: (res) => {alert(res);
          }
        })
      }, 2000)



      // 注册
      $("#register").on("click", () => {
        ajax({
          url: "http://localhost:8020/register",
          type: "get",
          data: {
            "userName": user.value,
            "password": pass.value
          },
          success: (res) => {alert(res);
          }
        })
      })

      // 登录
      $("#login").on("click", () => {console.log(remberPassword.checked);
        ajax({
          url: "http://localhost:8020/login",
          type: "get",
          data: {
            "userName": user.value,
            "password": pass.value,
            "isCookie": remberPassword.checked

          },
          success: (res) => {alert(res);
          }
        })
      })
    })

nodejs

var express = require("express");
var cookieParser = require("cookie-parser");
var static = require("express-static");
var fs = require("fs");

var server = express();
server.listen(8020);

server.use(cookieParser("asdfghjklpoiuytrewqasdgh1234567"));
// // 注册
server.use("/register", (req, res) => {
  let userMessage = req.query;
  fs.readFile("../user.txt", "utf8", (err, data) => {if (err) console.log(err);
    let user;
    if (data) {user = JSON.parse(data);
    } else {user = {};
    }
    if (user[userMessage.userName]) {res.send("用户已存在");
      return;
    } else {user[userMessage.userName] = userMessage.password;
      fs.writeFile("../user.txt", JSON.stringify(user), (err, data) => {if (err) {console.log(err);
        }
        res.send("注册成功");
      });
    }
  });
});

/* 
  1 种一个 cookie,res.cookie("cookie 名","cookie 内容",{path: 路径,signed: 是否加密,maxAge: 超时时间})
  2 cookie 加密,req.secret 规定一个加密规则,然后 res.cookie("cookie 名","cookie 内容",{path: 路径,signed:true,maxAge: 超时时间})
  3 获取 cookie, 利用 cookie-parser, 先声明 server.use(cookieParser()); 获取,req.cookies;
  4 cookie 解密:server.use(cookieParser("asdfghjklpoiuytrewqasdgh1234567")); 在使用 cookieparser 中间件的时候,告诉 cookieparse 你的加密规则, 然后使用 req.signedCookies
*/

// 登录
server.use("/login", (req, res) => {
  let userMessage = req.query;
  req.secret = "asdfghjklpoiuytrewqasdgh1234567";
  fs.readFile("../user.txt", "utf-8", (err, data) => {if (err) console.log(err);
    let userData = JSON.parse(data);
    if (userData[userMessage.userName] == userMessage.password) {if (userMessage.isCookie) {
        res.cookie("user1", userMessage.userName + "-" + userMessage.password, {
          signed: true,
          maxAge: 60 * 1000,
        });
      }
      res.send("登录成功");
    } else {res.send("登录失败");
    }
  });
});

// 自动登录
server.use("/auto", (req, res) => {
  let cookies = req.signedCookies;
  console.log(cookies);
  if (cookies.user1) {let userMessage = {};
    userMessage.userName = cookies["user1"].split("-")[0];
    userMessage.password = cookies["user1"].split("-")[1];
    req.secret = "asdfghjklpoiuytrewqasdgh1234567";
    fs.readFile("../user.txt", "utf-8", (err, data) => {if (err) console.log(err);
      let userData = JSON.parse(data);
      if (userData[userMessage.userName] == userMessage.password) {res.send("登录成功");
      }
    });
  } else {res.send("登录超时, 请重新登录");
  }
});

server.use(static("./../"));

效果:

正文完
 0