req.variable 存储在哪里?

Where is req.variable stored?

类似的问题(但不是重复的):How do i store request-level variables in node.js?

考虑以下代码:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
   req.someVariable = "Hello";
   res.send(req.someVariable + ' world!');
});

req.someVariable 存储在哪里?在饼干里?这仅适用于用户还是所有人?另外,这些和存储在 sessions/cookies 中有什么区别?

除了 req 只是一个 javascript 对象变量,存储在内存中,请注意 express 还有一个 res.locals 对象变量,它在 request/response 循环中持续存在.

如果您想存储任何用户信息,您应该使用 res.locals 对象,以免意外覆盖其他重要对象。

res.locals

An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals. This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.

http://expressjs.com/en/5x/api.html#res.locals

app.use(function (req, res, next) {
  res.locals.user = req.user
  res.locals.authenticated = !req.user.anonymous
  next()
})

注意:res.locals 本身不会与响应一起发送(例如 res.send)。它只能在您的 nodejs 应用程序中访问。

Cookies

Cookie 是您要发送到客户端浏览器的信息位(存储在浏览器内存中)。然后客户端可以将 cookie 发送回您的 nodejs 应用程序。这些不同于 reqres 属性。

Cookie 可以存储例如身份验证令牌,它可以存储在客户端的浏览器中,并在每次请求时提供给 nodejs 应用程序。

为了安全,您可以使用不能被浏览器修改的 httpOnly cookie javascript。