express跨域设置cookie完成用户免登录

一个用户免登录的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();
});
遇到的问题
  1. 使用cookieParser插件时是app.use(cookieParser()),里面有**()**的,一开始我没加上括号,一直执行不出来
  2. 因为用的是POST请求,所以要使用body-parser插件,把参数拿出来
  3. 没有使用数据库,使用写死了的用户名
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值