You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用NodeJS与JavaScript实现按用户会话单独存储日志的方案咨询

按用户会话拆分日志实现方案

方案适配性说明

express的session模块完全匹配你的使用场景,该模块会为每个独立访问用户生成唯一的会话ID(sessionID),你可以直接用这个ID作为日志文件名的区分标识,实现不同用户的操作日志分开存储。

注意:默认session存储在服务端内存中,仅适合小流量测试场景,生产环境建议对接redis、mysql等持久化存储介质,避免服务重启后会话丢失。

改造步骤

  • 首先安装session依赖:
    npm install express-session
  • 服务端引入并配置session中间件,开启https适配的cookie配置
  • 修改POST接口的日志写入逻辑,将日志文件名和当前请求的sessionID绑定
  • 调整前端fetch请求配置,新增会话cookie携带参数,避免同个用户每次请求生成新的会话ID

完整修改代码示例

服务端代码

const app = require('express')();
const https = require('https');
const fs = require('fs');
const session = require('express-session');

// 配置session中间件
app.use(session({
  secret: '自行替换为随机加密字符串',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true } // 适配HTTPS场景,仅在HTTPS请求下携带cookie
}));

app.get('/', (req, res) => {
    res.writeHead(200, {'Content-Type': 'text/html'});
  var readStream = fs.createReadStream('index.html','utf8');
  readStream.pipe(res);
});

app.post('/:fieldName/:flag/:time', (req, res) => {
    console.log('POST message received', req.params, req.sessionID);
    if (req.params && req.params.fieldName) {
        const logPath = `./changeLog_${req.sessionID}.csv`;
        // 首次写入时新增CSV表头
        if (!fs.existsSync(logPath)) {
            fs.writeFileSync(logPath, 'fieldName,flag,time\r\n', 'utf8');
        }
        // appendFileSync为同步方法,无需加await
        fs.appendFileSync(logPath, `${req.params.fieldName},${req.params.flag},${req.params.time}\r\n`, 'utf8');
    }
    res.sendStatus(200);
});

https.createServer({
    pfx: fs.readFileSync('<path>'),
    passphrase: '<phrase>'
}, app).listen(3000);

前端监听函数代码

let unregisterHandlerFunction = worksheet.addEventListener(tableau.TableauEventType.FilterChanged,(filterEvent) => {
  let changeMessage = filterEvent.fieldName + ' filter changed on ' + getDateTimestamp()
  fieldIndicator = 'Filter'
  time = getDateTimestamp()
  const details = {
    method: 'POST',
    credentials: 'include' // 新增配置,允许fetch请求携带会话cookie
  };
  fetch(`https://<url>/${filterEvent.fieldName}/${fieldIndicator}/${time}`, details).then((res) => {console.log(res);});
});

内容的提问来源于stack exchange,提问作者530529

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 08:54:04