Express 中间件在我 post 表单后丢失 res.locals
Express middleware lose res.locals after I post form
我有一个 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 请求执行的?
谢谢!
由于您的表单正在发送 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();
});
我希望这会解决问题,如果不能解决请告诉我。
我有一个 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 请求执行的?
谢谢!
由于您的表单正在发送 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();
});
我希望这会解决问题,如果不能解决请告诉我。