Sunday 19 March 2017

Node JS EJS get URL parameters

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



via GatorFlores

No comments:

Post a Comment