简体   繁体   English

Express.JS:将 cookie 附加到静态提供的内容

[英]Express.JS: Attach cookie to statically served content

I use Express.JS to serve static content:我使用 Express.JS 提供 static 内容:

express.use(express.static('./../'));

When index.html is served, I would like to send a cookie alongside the response indicating if the user is signed in or not.index.html提供服务时,我想在响应中发送一个 cookie,指示用户是否登录。 Normally one should use res.cookie() but I cannot see how to use it for statically served content.通常应该使用res.cookie()但我看不到如何将它用于静态提供的内容。

Not sure why you need to do this, but you can place your own middleware before the static module. 不知道为什么需要这样做,但是可以将自己的中间件放在static模块之前。

The following quick hack should work: 以下快速技巧应该可以起作用:

function attach_cookie(url, cookie, value) {
  return function(req, res, next) {
    if (req.url == url) {
      res.cookie(cookie, value);
    }
    next();
  }
}

app.configure(function(){
  app.use(attach_cookie('/index.html', 'mycookie', 'value'));
  app.use(express.static(path.join(__dirname, 'public')));
});

The above inserts another function in the chain of middleware express uses before the static middleware. 上面在static中间件之前在中间件表达使用链中插入了另一个功能。 The new layer attaches the cookie to the response if the URL matches the specific one you are looking for -- and passes the response further down the chain. 如果URL与您要查找的特定URL匹配,则新层将cookie附加到响应中,并将响应进一步传递到链下。

Consider also the following approach: 还考虑以下方法:

  1. If your express is behind web-server you can serve static files without bothering express - it should be faster than via middle-ware. 如果您的快递服务落后于Web服务器,则可以投放静态文件而不会打扰快递服务-它应该比通过中间件更快。 If you use nginx, this can help: Nginx Reverse Proxying to Node.js with Rewrite . 如果使用nginx,这将有所帮助: Nginx使用Rewrite反向代理到Node.js。

  2. Assuming that your static file has javascript in it, you can also set cookies directly on the client side only requesting from express the data you need for this cookie: 假设您的静态文件中包含javascript,您也可以直接在客户端设置cookie,仅从表达请求此cookie所需的数据中进行请求:

     document.cookie = "user_id=" + user_id; 

    Flanagan's JS definitive guide (edition 6!) has an excellent coverage on how to use cookies in client-side javascript (in addition to being the best among JavaScript books :). Flanagan的JS权威指南(第6版!)很好地介绍了如何在客户端javascript中使用cookie(除了在JavaScript书籍中是最好的:)。

It can be a trivial advice, but I have seen the following flow (more than once): client sends API request (which has a cookie attached to it, obviously), server gets data from the cookie and serves the response completely built on the data contained in this cookie. 这可能是一个微不足道的建议,但我已经看到了以下流程(不止一次):客户端发送API请求(很明显地,它附加了一个cookie),服务器从cookie获取数据并完全基于Cookie中包含的数据。 All this instead of just quietly reading this cookie in the client. 所有这一切,而不仅仅是在客户端静默读取此cookie。 Basically client asks the server what it has in its own cookie. 基本上,客户端会询问服务器它自己的cookie中包含什么。

In your scenario you need to request user_id/access_key only once and then always check the cookie in the client, going to the server only for the data that client doesn't already have, but storing and checking session state and, maybe, some compact data used in most pages (such as username, eg) in cookies locally (you can also cache data in local storage, to reduce the server load even further). 在您的方案中,您只需要请求一次user_id / access_key,然后始终检查客户端中的cookie,仅将客户端不具有的数据转到服务器,而是存储和检查会话状态,并且可能紧凑大多数页面在本地Cookie中使用的数据(例如用户名)(您也可以将数据缓存在本地存储中,以进一步减轻服务器负载)。 In this case, express won't even know if a user accidentally refreshes the page (if you don't change URLs to reflect application state as well, of course, or only change #-part). 在这种情况下,express甚至都不知道用户是否意外刷新了页面(当然,如果您也没有更改URL以反映应用程序状态,或者仅更改#-part)。

As app.configure was removed since Express.js v4, I would like to do an update. 由于自Express.js v4起删除了 app.configure,因此我想进行更新。

For Express.js versions > 4, to initialise my app by passing options inside the express.static(root, [options]) method, in which you can pass a Set-Cookie header in the property called setHeaders : 对于大于4的Express.js版本,通过在express.static(root, [options])方法内传递选项来初始化我的app ,在该方法中,您可以在名为setHeaders的属性中传递Set-Cookie标头:

app.use(express.static(publicPath, {
  setHeaders: function (res, path, stat) {
    res.set('Set-Cookie', "myCookie=cookieValue;Path=/")
  }
}));

It is important to set Path=/ because otherwise express will create numerous duplicates of the cookie on the client side. 设置Path=/很重要,因为否则express会在客户端创建大量cookie的副本。

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

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