【问题标题】:Node : How to identify if any user is opening the website more than one time节点:如何识别是否有用户多次打开网站
【发布时间】:2021-09-24 12:20:17
【问题描述】:

如何使用 node/express 后端识别同一用户是否正在打开网站? 我尝试设置一个 cookie,但不知道为什么它会被自动删除

【问题讨论】:

    标签: node.js express web


    【解决方案1】:

    这只是你如何实现它的一个示例。

    首先安装这个 npm 包:

    npm install express cookie-parser

    然后是一般设置:

    const express = require('express')
    const cookieParser = require('cookie-parser')
    
    //to setup express app
    const app = express()
    app.use(cookieParser());
    

    引导你喜欢的其余部分。

    这是 cookie 的重要部分:

    //an example route for setting cookies
    app.get('/setcookie', (req, res) => {
        res.cookie(`Cookie token name`,`encrypted cookie string Value`,{
            maxAge: 5000,
            // expires works the same as the maxAge
            expires: new Date('01 12 2021'),
            secure: true,
            httpOnly: true,
            sameSite: 'lax'
        });
        res.send('Cookie have been saved successfully');
    });
    

    如果您愿意,您可以使用此路由从您的浏览器检查 cookie(或者如果您的 cookie 名称已设置,请查看开发人员工具):

    // get the cookie incoming request
    app.get('/getcookie', (req, res) => {
        //show the saved cookies
        console.log(req.cookies)
        res.send(req.cookies);
    });
    

    所以简而言之,这应该可以解决问题:)

    More details and examples of this approach can be found here.

    【讨论】:

      猜你喜欢
      • 2011-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多