gpt4 book ai didi

javascript - 使用 express 中间件设置 cookie

转载 作者:行者123 更新时间:2023-11-30 14:32:22 24 4
gpt4 key购买 nike

我尝试通过扩展 apostrophe-express 模块在页面加载时设置 cookie。但是控制台显示错误......在成功输出 req.cookies 到它之后。

部分模块的index.js:

module.exports = {
extend: 'apostrophe-express',
// [...]
middleware: [
function(req, res, next) {
console.log(req.cookies); // Successful output.
return next(); // App crashes.
}
]
};

控制台输出;用户、应用程序和 cookie 值已替换:

{ '[app].csrf': '[randomString]',
'[app].sid':
'[someId]' }
/Users/[user]/Node/[app]/node_modules/apostrophe/lib/modules/apostrophe-templates/index.js:608
req.browserCall('apos.pageReadyWhenCalm($("body"));');
^

TypeError: req.browserCall is not a function
at Object.self.renderPageForModule (/Users/[user]/Node/[app]/node_modules/apostrophe/lib/modules/apostrophe-templates/index.js:608:13)
at /Users/[user]/Node/[app]/node_modules/apostrophe/lib/modules/apostrophe-module/index.js:349:31
at /Users/[user]/Node/[app]/node_modules/async/lib/async.js:726:13
at /Users/[user]/Node/[app]/node_modules/async/lib/async.js:52:16
at /Users/[user]/Node/[app]/node_modules/async/lib/async.js:264:21
at /Users/[user]/Node/[app]/node_modules/async/lib/async.js:44:16
at /Users/[user]/Node/[app]/node_modules/async/lib/async.js:723:17
at /Users/[user]/Node/[app]/node_modules/async/lib/async.js:167:37
at /Users/[user]/Node/[app]/node_modules/apostrophe/index.js:128:16
at /Users/[user]/Node/[app]/node_modules/async/lib/async.js:52:16
at /Users/[user]/Node/[app]/node_modules/async/lib/async.js:264:21
at /Users/[user]/Node/[app]/node_modules/async/lib/async.js:44:16
at Immediate.<anonymous> (/Users/[user]/Node/[app]/node_modules/apostrophe/index.js:429:20)
at runCallback (timers.js:696:18)
at tryOnImmediate (timers.js:667:5)
at processImmediate (timers.js:649:5)

我错过了什么? This answer是我的中间件功能的基础。

编辑:设置 cookie 后返回 res.send('ok') 也会发生同样的情况。

最佳答案

要以正确的方式使用 express 中间件,必须设置 expressMiddleware 属性。

afterConstruct: function(self) {
self.expressMiddleware = function(req, res, next) {
res.cookie('cookieName', 'value');
return next();
};
}

这会在浏览器中设置一个 cookie 并继续下一个中间件。

expressMiddleware 是每个模块都有的属性。无需扩展 apostrophe-express

如果我错了,请加强这个答案,关于这个话题还有更多要说的或者存在更好的方法。

关于javascript - 使用 express 中间件设置 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50976682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com