一个用户免登录的demo,前台页面在5500端口,后台代码在3000端口
运行结果
前期准备
下载node相关依赖
cnpm install express,body-parser,cookie-parser //镜像地址下载比较快
前台页面准备
用于登录的页面cookieLogin.html
<!--
* @Author: army liu
* @Date: 2020-11-22 13:47:37
* @LastEditors: army liu
* @LastEditTime: 2020-11-22 16:01:18
* @FilePath: \font\cookieLogin.html
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./js/jquery-1.11.0.min.js"></script>
</head>
<body>
<div>
用户名: <input type="text" id="name"><br>
密 码:<input type="password" id="password"><br>
<button id="btn">提交</button>
</div>
<script>
window.onload = () => {
function fidCookie(name){
let cookieArr = document.cookie.split("; ");
let Obj = {}
for(let val of cookieArr){
let temp = val.split("=");
Obj[temp[0]] = temp[1];
}
return Obj[name];
}
if(fidCookie("username")){
window.location.href = '/cookieIndex.html'
}
$('#btn').on('click', function () {
let name = $('#name').val();
let pwd = $('#password').val();
console.log(name, pwd)
$.ajax({
type: "post",
url: "http://127.0.0.1:3000/login",
data: {
name,
pwd
},
xhrFields: {
withCredentials: true
},
crossDomain: true,
success: function (response) {
console.log(response)
window.location.href = '/cookieIndex.html'
}
});
})
}
</script>
</body>
</html>
用于显示登录成功的页面cookieIndex.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./js/jquery-1.11.0.min.js"></script>
</head>
<body>
<h1>我是cookie页面</h1>
<script>
function fidCookie(name) {
let cookieArr = document.cookie.split("; ");
let Obj = {}
for (let val of cookieArr) {
let temp = val.split("=");
Obj[temp[0]] = temp[1];
}
console.log(Obj)
return Obj[name];
}
let h1 = document.createElement('h1');
h1.innerHTML = "你好," + fidCookie("username")
document.body.appendChild(h1)
</script>
</body>
</html>
特别说明
我使用了ajax
发送数据,因为后台端口和前台端口是不一样的,使用需要在ajax
设置
xhrFields: {
withCredentials: true
},
crossDomain: true,
否则是无法在后台设置cookie
的
后台搭建
后台使用了node的express
框架
/*
* @Author: army liu
* @Date: 2020-11-22 13:50:17
* @LastEditors: army liu
* @LastEditTime: 2020-11-22 16:21:47
* @FilePath: \font\js\cookieTest.js
*/
let express = require('express');
let app = new express();
const bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
let cookieParser=require("cookie-parser")
// cookieParser记得要加()
app.use(cookieParser())
//需要安装并且引入中间件cors
const cors = require('cors');
var corsOptions = {
origin: 'http://127.0.0.1:5500',
// 允许跨域情况下发送cookie
credentials: true,
maxAge: '1728000'
}
app.use(cors(corsOptions))
app.post('/login', function(req, res){
let name = req.body.name;
let pwd = req.body.pwd;
console.log(name, pwd)
if(name == "Larmy" && pwd==123){
res.cookie('username',"Larmy")
res.cookie('login',true)
console.log("111")
console.log(req.cookies)
res.send({
msg:'success',
code:200
})
res.end()
}
})
app.get('/cookie', function(req, res){
console.log();
res.send(req.cookies)
})
// 监听端口
app.listen(3000,() => {
console.log("3000端口已启用")
})
如果不想使用cors
,也可以自己进行配置
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("Access-Control-Allow-Credentials", true);
next();
});
遇到的问题
- 使用
cookieParser
插件时是app.use(cookieParser())
,里面有**()**的,一开始我没加上括号,一直执行不出来 - 因为用的是
POST
请求,所以要使用body-parser
插件,把参数拿出来 - 没有使用数据库,使用写死了的用户名