TomK
TomK

Reputation: 127

URL Redirection handlers in NODE.JS & EXPRESS

I am trying to make a redirection function work using an html form that redirects to a specified URL

This is the "database" (just an object right now):

let urlDatabase = {
b2xVn2: "http://www.cbc.ca", //keyname just a randomly assigned number
"9sm5xK": "http://www.google.com"
};

and this is how said "database" is passed to the server:

app.get("/urls", (req, res) => {
//template vars is passed to urls_index EJS file
let templateVars = { urls: urlDatabase };   
res.render("urls_index", templateVars); 
});

"urls_index" being the view file....

and my form on the view ejs file (named "urls_index":

     <% for (let index in urls) { %>
     <ul> <li> <%=  urls[index] + ": " + index %>   <br>  
     <form method ="POST" action="/u/<%= urls[index] %>"><button 
     type="submit" class="btn btn-outline-danger btn-sm">Click here to 
      redirect to your page</button></form>

     </li> </ul>
     <% } %>

My handler on the Server file:

app.get("/u/:id", (req, res) => {
let redirection = urlDatabase[req.params.id];
res.redirect(redirection);
});

when the form is clicked, it should redirect to the corresponding url page (to redirect to google.com for example).

Any help is appreciated, thanks.

Upvotes: 1

Views: 62

Answers (1)

Lord Elrond
Lord Elrond

Reputation: 16032

ejs uses the awful javascript for loops, and not the for x in y loop like in python.

This should fix the problem:

<% for (var i=0; i<urls.length; i++) { %>
<ul> <li> <%=  url[i] + ": " + i %>   <br>  
<form method ="GET" action="<%= '/u/' + url[i] %>">
<button class="btn btn-outline-danger btn-sm">Click here to redirect to your page</button> 
//buttons have a default type="submit" so no need to add that
</form>

 </li> </ul>
 <% }; %>

Note that you can also use a for loop like this if the array index is not needed:

<% urls.forEach(function(url) { %>

//do something with url

<% }); %>

Upvotes: 1

Related Questions