首页 > 解决方案 > 设置为 express req 对象的标头不会跨路由保留

问题描述

我正在尝试在我req的 express 对象中设置 sessionId 以用于其他路由。当我通过中间件设置它时,它可以工作,如果通过路由尝试相同,它就不起作用。

我试图使路由方法起作用,因为我试图在我的req对象中设置一个“sessionId”,这个 sessionId 是基于用户名的。因此,我想要工作的路线方法。

req我尝试使用而不是对象,res.locals但我面临同样的问题。我在这里想念什么?

当我说它不起作用时,我的意思是如果我尝试通过req.headers.sessionid其他路线访问,它就是undefined.

index.js

const express = require('express')
const app = express()
const setSessionId = require('./setSessionId');

app.use(function(req, res, next){ // this works...
    const { username } = req.body;
    req.headers.sessionid = crypto.createHash("sha256").update('Temp Name').digest("hex"); // to be replaced by corpId;
    next();
})
app.use('/login',setSessionId);

setSessionId.js

const express = require('express');
const router = express.Router();
const crypto = require('crypto');

router.post('/success', (req, res) => { // this doesnt work...
    const { username } = req.body;
    req.headers.sessionid= crypto.createHash("sha256").update(username).digest("hex"); // to be replaced by corpId;
    res.send(req.headers.sessionid);
});

module.exports = router;

标签: javascriptnode.jsexpresssessionrouting

解决方案


这是问题所在,您既不想使用 cookie 也不想缓存,但您需要跨多个请求跟踪资源。我可以建议您依赖 HTTP 自定义标头吗?

如何

首先,编写请求拦截器中间件function以检查自定义标头是否存在。如果没有就追加。然后编写响应拦截器function以附加自定义标题。

例如

// request interceptor middleware function to append custom header.
// **Note** By convention, custom header starts with "X-"
// visit: https://tools.ietf.org/html/rfc6648
const interceptReqForSessionId = (req, res, next) => {
  req.headers['X-Session-ID'] =
     req.headers['X-Session-ID'] ||
     crypto.createHash("sha256").update(username).digest("hex");
  next();
};

// response interceptor middleware function to append custom header.
// Client will be required to pass this header in the subsequent requests
const interceptResForSessionId = (req, res) => {
  res.header('X-Session-ID', req.headers['X-Session-ID'])
     .send(req.data);
};  

接下来,在适当的路由之前和之后使用注册拦截器。

router.post(interceptReqForSessionId, (req, /*res*/_, next) => {
  // rest of your code... req.headers[X-Session-ID] gives you the ID
  // do not return result immediately. Call next
  next();
}, interceptResForSessionId);

推荐阅读