0

i develop web system in PHP and now i'm very excited with NODEJS.

Even though it is not a good practice, in my view, many times do that:

If the user is not logged in, them redirect.

<?php

  session_start();

    if(!isset($_SESSION['login']) || 4 !== (integer)$_SESSION['id_perfil_sistema']){
        header("Location: /vault/");
    }

?>

And other times I get the session data to customize the page according to the logged User

<li style="background-color:#ddd;"> <a style="color:blue;" href="#"> <?php echo ucwords($_SESSION['nomeusuario']); ?> </a> </li>

<input type="hidden" name="theOrigin" value="<?=$_SESSION['origin'];?>" />

<script type="text/javascript">
     var x = <?php echo $_SESSION['session_variable']; ?>;
</script>

I have learned to create session in nodejs. =)

What best way to get session nodejs in javascript ?

I'm using nodejs and express.

kind regards

1
  • did this help at all? Commented Mar 4, 2016 at 14:23

1 Answer 1

2

You should be able to get session from any request object, once you have included the express session middleware (https://github.com/expressjs/session)

For example redirecting all non-logged in users to '/login', can be written as express middleware on each request like this:

app.use(function(req, res, next) {
  if(!req.session.login){
      res.redirect("/login");
      return;
  }
  next();
});

and to add session to markup (assumes using Jade or other express templating middleware)

JS

app.get('/', function (req, res) {
   res.render('index', { nomeusuario: req.session.nomeusuario });
});

Jade (example)

html
  body
    h1= nomeusuario

Note: Code not tested, just an example

Sign up to request clarification or add additional context in comments.

1 Comment

Great answer, @Ollieh! @felipe-muner, I recommend you jade templating for: code readability, coding productivity, child-to-parent layout usage (you define layout filling in extenders) and more. A plus: you can use config package to define resource paths (using CDN? Use it!) and general application configuration.

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.