简体   繁体   中英

Passing Variables from Node / Express to AngularJS

I am wondering how I can pass variables from Node / Express to my AngularJS 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 "/" AngularJS 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;
}

I think that the best practice is to implement an api that returns all the data you need with an ajax request. But if you don't want to the all that work, you can add an hidden input element to your page and set his value with a json string that later can be parsed to js an object in your client side.

I'm pretty sure with passport, that the user information is in the request object.

Meaning, you should be able to access through req.user.name , etc.

You could then send it to angular in response " res.send({currentUser: req.user})" when needed, or possibly in your login and store it in rootscope or localStorage / cookie

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM