Home > Mobile >  How to res.render/send a variable after a redirect?
How to res.render/send a variable after a redirect?

Time:09-24

I want to send a message variable that says something like succeeded or failed wihtout the use of passport or sessions.

When it fails I can just do this:

res.status(401).render('register', {
    message: 'Your username/email or password is incorrect.'
})

So I was thinking this was possible:

res.redirect('/');
res.render('', { message: 'Login success.'});

But it turns out it isn't:

Error: Cannot set headers after they are sent to the client

Are there any simple sollutions?

I tried making a router.get('/message/redirect :route') but I realised I ran into the same problem there too.

CodePudding user response:

You are redirecting before rendering. So the render method can't send headers because you have already redirected them. You need to call either redirect or render, not both at once. you can do it like this.

res.render('/', { message: 'Login success.'});

remove this line

res.redirect('/');

In your EJS file just call <%= message %> to access the message. There is a better way of dealing with confirmation/error messages. Use Flash.

npm install express-flash

Then before rendering, call the flash. Flash takes two arguments, a name of the message and the message itself, Like this

req.flash("MessageName", "Login success");
res.redirect(pathName);

Make sure to use flash

const flash = require('express-flash');
app = express();
app.use(flash());

app.use((req, res, next) => {
    res.locals.MessageName= req.flash("MessageName");
    next();
});

To access the message in EJS file just call <%= MessageName %>

Here is sample from my code: In the server file:

req.flash("error", "Something went wrong");
res.redirect('back');

In the EJS file:

<div class="flash">
    <% if(error && error.length > 0){ %> 
        <div class="flash_error">
            <h1 class="flash_error--text"><%= error %></h1> 
        </div>
    <% } %> 
</div>

Read this for more information

  • Related