【问题标题】:Express middleware lose res.locals after I post form在我发布表单后,Express 中间件丢失 res.locals
【发布时间】:2021-01-10 17:24:57
【问题描述】:

我有一个 Express 应用程序,它可以选择切换主题,我使用全局中间件来实现它:

app.get('*', (req, res, next) => {
    req.session.theme = req.query.theme || req.session.theme || 'light';
    res.locals.theme = req.session.theme;
    next();
});

app.use('/contact', require('./routes/contact.route'));

主题在所有视图中都可用,但我有两个带有联系表单的视图,在我提交此表单后 主题不可用

我在 ejs contact.ejs 和 header.ejs 中是这样使用的:

<div class="g-recaptcha" data-sitekey="<%=captcha%>" data-theme="<%= theme %>"></div>
<link rel="stylesheet" href="/css/theme-<%=theme%>.css" type="text/css" />

问题是执行中间件引起的,这个中间件在我提交表单后没有执行 app.get('*' ...

这是因为 app.get('*') 中间件只是针对 GET 请求执行的吗?

谢谢!

【问题讨论】:

  • 既然您要发布表单,您是否尝试过将app.get('*',/* rest */) 更改为app.post('*',/* rest */)

标签: node.js express ejs


【解决方案1】:

当您的表单正在发送 post 或 put 请求时,您的 app.get() 没有在表单提交中执行。

只需将您的代码更改为此

app.use( (req, res, next) => {
    req.session.theme = req.query.theme || req.session.theme || 'light';
    res.locals.theme = req.session.theme;
    next();
});

我希望这能解决问题,如果没有,请告诉我。

【讨论】:

    猜你喜欢
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    • 2010-11-14
    • 2016-01-31
    • 2012-04-01
    • 1970-01-01
    相关资源
    最近更新 更多