1

I'm trying to read URL parameters in an EJS template, however everything I try or read from google isn't working. Here's the relevant part of my app.js file:

app.post('/account/logintoaccount', function(req, res) {
    var email = req.body.email;
    if(email === '') {
        res.redirect('https://myurl.com/account/login?e=bademail');
        return;
    }
    var password = req.body.password;
    if(password === '') {
        res.redirect('https://myurl.com/account/login?e=badpassword');
        return;
    }
    res.redirect('https://myurl.com/?email=' + email + '&pw=' + password);
});

And here's where I'm trying to display the variable in my EJS file:

<div id="title-text">
    <% if(!req.query.e) { %>
        <p>Log into your account:</p>
    <% } else if(req.query.e === "badpass") { %>
        <div class="alert alert-danger"><strong>Error</strong> incorrect password</div>
    <% } else if(req.query.e === "bademail") { %>
        <div class="alert alert-danger"><strong>Error</strong> unknown email address</div>
    <% } %>
</div>

If I remove this part of my EJS file my redirects work fine. The URL has the parameters in it and all is good. However whenever I try and use my URL parameters in any way shape or form in my EJS file it breaks and gives me an "X is undefined error". I've tried using 'e', 'req.query.e', 'this.e', 'this.req.query.e' and anything else that google results have suggested I do.

My end goal is to be able to read the URL parameters in https://myurl.com/account/login?e=somethinghere

Then check what 'e' holds. I've spent the last 30+ minutes reading over google results however I believe they're either outdated or I'm just doing them wrong. Can anyone help please? Thank you for your time

2
  • You need to show your GET /login handler. You are probably not passing the request object to your view. Commented Mar 20, 2017 at 0:58
  • @Mikey app.get('/account/:action', function(req, res) { res.render('account/' + req.params.action, { session: req.session }); }); This? If so what would I add to fix this? Thanks Commented Mar 20, 2017 at 1:02

1 Answer 1

1

Just pass the request into your view

app.get('/account/:action', function(req, res) { 
   res.render('account/' + req.params.action, { 
      session: req.session,
      req: req
   });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Word of advice, it's better to store your errors in the session instead. Also, it's never a good idea to put a password in the URL.
@AlexzanderFlores : did you redirect or render . While using redirect how can we extract the query values in the ejs template

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.