最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing Variables from NodeExpress to AngularJS - Stack Overflow

programmeradmin0浏览0评论

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 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;
}
Share Improve this question edited Jan 9, 2019 at 22:37 Félix Paradis 6,1016 gold badges44 silver badges53 bronze badges asked Jun 25, 2016 at 20:51 MadPhysicistMadPhysicist 5,84113 gold badges49 silver badges121 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

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.

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

发布评论

评论列表(0)

  1. 暂无评论