我正在尝试在我的express的req
对象中设置sessionId以在其他路由中使用。当我通过中间件进行设置时,它可以工作;如果通过路由尝试同样的操作,则不起作用。
我正在尝试使路由方法起作用,因为我正在尝试在req
对象中设置一个'sessionId',该sessionId基于userName。因此,我希望使用路由方法。
[不是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;
这里是问题,您既不想使用cookie也不缓存,但是需要跟踪多个请求中的资源。我可以建议您依赖HTTP自定义标头吗?
How
首先,编写请求拦截器中间件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);