Ask coding questions

← Back to all posts
Variable Names when using sendFile in Node.js Express
kaskie (1)

Hey all!
First post here. I'm trying to link the '/' page to a different page depending on the value of a variable, but it doesn't seem to work. I tried using true and false for the loggedIn variable, but that linked '/' to main.html under the private folder. I edited a bit, but this current revision still gives the same result.
Thanks,
Kaskie

Answered by notGilbert (121) [earned 5 cycles]
View Answer
Comments
hotnewtop
notGilbert (121)

You aren't running the if everytime the page is being requested

Try putting the if statement inside the get handler

ie:

app.get('/'. (req, res) => {
  if (checkLoggedIn(req)) {
    res.sendFile('[insert protected page here]');
  } else {
    res.sendFile('[insert log in page here]');
  }
})

right now you're only running the check once, meaning that every request after will return the same content

also fix your if statement, use === or == as they are comparison, = is assignment

kaskie (1)

@notGilbert Ah, thanks so much! Also, I would've driven myself crazy if you hadn't reminded me of ==, so thanks for that as well

alanchen12 (32)

You can also use middleware ex:

const checkLoggedIn = (req, res, next) => {
  // check if logged in here
  if (loggedIn) return next()
  else // do something if the user isnt logged in
}
app.get('/', (req, res) => {
  // send homepage here
})
app.get('/login', (req, res) => {
  // make the user logged in here
})
app.get('/myProtectedpage', checkLoggedIn, (req, res) => {
  res.sendFile('')
})

However, instead of using a varaiable to check if logged in i recommend using express-session
@kaskie