简体   繁体   English

如何将会话和Cookie用于express.use(express.static('static'))?

[英]How do I use session and cookies for express.use(express.static('static'))?

I have a question about session cookies over web from express backend. 我有一个关于来自后端的网络会话cookie的问题。 In the front I am using a Vue PWA/SPA that is being mounted on express static via express.use(express.static('static')); 在前面,我使用的是Vue PWA / SPA,它已通过express.use(express.static('static'));安装在express static上express.use(express.static('static')); to serve the built files. 服务生成的文件。

I did some research that we can attach options to the function with 我做了一些研究,我们可以将选项附加到

express.use(cookieParser());
express.use(session({
  secret : `${uuid()}`,
  proxy: true,
  resave: false,
  saveUninitialized: false,
  cookie: {
    maxAge: 1000 * 60 * 30
  }
}))

const options = {
  dotfiles: 'ignore',
  etag: false,
  extensions: ['html', 'htm'],
  index: false,
  maxAge: '1d',
  redirect: false,
  setHeaders: function(res, path, stat) {
    res.set('Set-Cookie', "myCookie=cookieValue;Path=/");
    res.set('x-timestamp', Date.now());
  }
}
express.use(express.static('static' , options));

After doing those, hoping I can read myCookie=cookieValue on the browser via document.cookie but I don't see those datra being printed on the page. 完成这些操作之后,希望我可以通过document.cookie在浏览器上读取myCookie=cookieValue ,但是我看不到这些数据打印在页面上。

I have also tried it with __dirname method as well and then do 我也用__dirname方法尝试过,然后做

app.get("/", function(req, res) {
  req.session.fullname = "Oh mi gee";
  res.render("index");
});

didn't give me what I want. 没有给我我想要的东西。 Is there a way for me to add session/cookies so I can somewhat secure the API calls by passing cookie data on the header for confirmation? 我是否可以添加会话/ Cookie,以便通过在标头上传递Cookie数据进行确认来确保API调用的安全性?

Thanks in advance! 提前致谢!

I have figured it out, is to place this express.static at the very end of the express configuration. 我已经弄清楚了,就是将这个express.static放在express配置的最后。

before we establish express.static we will want to do 在建立express.static之前,我们将要做

app.use('/path', (req, res, next) => {
  req.session.views++;
  res.cookie('myCookie', 'cookieValue', {
    maxAge: 1000 * 60 * 30
  });
  console.log(req.session);
  next();
})

will transfer the cookies to the client side with the expiry of half an hour. 将在半小时后将Cookie传输到客户端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM