MadPhysicist MadPhysicist - 5 months ago 77
AngularJS Question

Passing Variables from Node / Express to Angular

I am wondering how I can pass variables from Node / Express to my Angular front end. In particular, if I am using Express (Passport) for authentication, how can I pass the user name and information to display in the corner of my app, alongside the "Logout" button?

Here is my code for authentication routes. Should I be using URL variables for this? Or should I try to somehow implement a separate end-point that would pass this small bit of info?

Just to clarify, once the user logs in and is directed to "/" Angular front-end takes over and does the routing within itself.

var express = require('express');
var router = express.Router();

module.exports = function(passport){

var isAuthenticated = function (req, res, next) {
// if user is authenticated in the session, call the next() to call the next request handler
// Passport adds this method to request object. A middleware is allowed to add properties to
// request and response objects
if (req.isAuthenticated()){
//console.log(next());
return next();
}
// if the user is not authenticated then redirect him to the login page
res.redirect('/login');
}


/* GET login page. */
router.get('/login', function(req, res) {
// Display the Login page with any flash message, if any
res.render('login', { message: req.flash('message') });
});

/* Handle Login POST */
router.post('/login', passport.authenticate('login', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash : true
}));

/* GET Registration Page */
router.get('/signup', function(req, res){
res.render('register',{message: req.flash('message')});
});

/* Handle Registration POST */
router.post('/signup', passport.authenticate('signup', {
successRedirect: '/',
failureRedirect: '/signup',
failureFlash : true
}));

/* GET Home Page when logged in */
router.get('/', isAuthenticated, function(req, res){
res.render('index', { user: req.user });
});

/* Handle Logout */
router.get('/signout', function(req, res) {
req.logout();
res.redirect('/login');
});

return router;
}

Answer

Short answer: Yes as you are using Express you should create a separate end-point to retrieve user data from your Angular app.

As another answer already states this user data should be stored in req.user.

So your end-point could look like this:

var express = require('express');
var isAuthenticated = require('path/to/exported/middleware').isAuthenticated;
var router = express.Router();

router.get('/user', isAuthenticated, function(req, res) {
    var data = {
        name: req.user.name,
        email: req.user.email,
        /* ... */
    };

    res.send({
        data: data
    });
});

module.exports = router;

Do not send the whole req.user object but select the properties you actually want to display.