javascript - 设置为 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;
解决方案
这是问题所在,您既不想使用 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);
推荐阅读
- mapbox - Mapbox 边界错误“402 - 需要付款”
- python - 使用 networkx 和 matplotlib 的网络平滑动画
- kotlin - 在 Kotlin 中,为什么 variable?.isNotEmpty() 会显示错误?虽然变量!!.isNotEmpty() 工作正常
- android - 无法在 tablayout 顶部隐藏行
- arduino - 为什么这个简单的代码打印错误的值
- docker - 具有默认秘密路径的 Hashicorp Vault 配置文件 (v1)
- amazon-web-services - 为什么 AWS ECS Fargate 没有实例类型?
- c++ - C++:再次输入 ComplexNumber(虚部和实部)运算符 ComplexNumber,依此类推
- php - 基于选项选择的表单操作更改仅在在家时有效
- python-3.x - Series 的真值是模棱两可的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all() 错误