Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...