Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

node.js - Express middleware lose res.locals after I post form

I have an Express app and this have option to switch theme and I implement this with a global middleware:

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'));

The theme it is available in all views, but I have two views with contact form and after I submit this form the theme is unavailable

I used like this in ejs contact.ejs and header.ejs :

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

And the problem it is caused by the executing middleware, this middleware it is not executed after I submit the form app.get('*' ...

This is because app.get('*') middleware it is executed just for GET requests?

Thank you!

question from:https://stackoverflow.com/questions/65651634/express-middleware-lose-res-locals-after-i-post-form

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As your form is sending the post or put request, which it should be, your app.get() is not executing in the form submission.

Just change your code to this

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

I hope that will fix the issue, if it doesn't please let me know.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...