Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Express Basics Deeper into Routing with Express Challenges: Redirects

Elena Medvedeva
Elena Medvedeva
9,555 Points

Is it possible to solve the redirection from the index page without the else clause

Is it possible to solve the redirection from the index page without the else clause Is there any mistake?

app.get('/', (req, res) => { const name = req.cookies.username; if (!name) { res.redirect('/hello'); } res.render('index', { name }); });

Am i right in thinking that redirecting stops the current function or not?

2 Answers

Hey elenmedvedeva2, you are correct.

app.get('/', (req, res) => {
    const name = req.cookies.username;

    if (!name) return res.redirect('/hello');
    res.render('index', { name });

});

But just to be safe, it's a good idea to use the 'return' keyword, just to ensure that the execution of the method after does indeed stop.

kieran venison
kieran venison
9,093 Points

I was thinking you could easily do this with a ternary operator. This is all well and good however you lsoe a bit of the readability

Something like this? I do like this..

!name ? res.redirect('/hello') : res.render('index', {name});

But I wouldn't say loss of readability could be considered here:

if (!name) return res.redirect('/hello');
res.render('index', { name });

If the name returns false, then the return statement is executed not allowing for the render to take place.. Using a ternary operator would just be a shorter way of doing this, which is not by much in comparison. And "shorter" does not necessarily mean more legible.

I used a ternary operator name ? res.render('index', { name }) : res.redirect('/hello'); I think this reads better than !name

Marko Delgadillo
Marko Delgadillo
4,524 Points

I actually added the logic to the post request 🤷🏽‍♂️

app.post("/hello", (req, res) => {
  res.cookie("username", req.body.username);
  if (req.body.username && /^[a-zA-Z]+$/.test(req.body.username)) {
    res.redirect("/");
  }
});

However, I understand why the solution was done on the GET request for the root since that is actually the home page. I will be changing my code 😃