使用Express中间件设置Cookie

时间:2018-06-21 20:04:20

标签: javascript node.js apostrophe-cms

我尝试通过扩展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')也会发生同样的情况。

1 个答案:

答案 0 :(得分:1)

要正确使用快速中间件,必须设置expressMiddleware属性。

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

这将在浏览器中设置cookie,并继续使用下一个中间件。

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

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