AngularJS - Access node/express session information

ぃ、小莉子 提交于 2019-12-07 12:12:11

问题


I am working on a node application that uses Express and Passport for authentication and authorization, and all of that is working properly. I am stumped, however, on how I would get the current user (set as req.user by Passport) in my Angular controllers.

I want to be able to do normal things like displaying the username in a header/navigation bar (among other things), and I am currently doing this using the Jade view engine, but I don't like mixing using the Jade view engine for some "data-binding" and Angular for others.

Now, I do know that I could easily make a call to an api endpoint in node that returns req.user as JSON, but that seems like an ugly solution, as I would be hitting that endpoint everytime there is a page load (this is not an SPA).

So my question basically is this: Can I get the currently logged in user in my Angular views so I can do all my data-binding client side instead of some server side (with the Jade view engine) and some client side with Angular?

Note: No code snippets because everything actually is working as intended, I'm just hoping for a better alternative than what I currently have.


回答1:


Consider using "ng-init" on the DOM that defines the ng-app, that is a server side data printed in Express (assume Dust template). Below is a simple example of this:

    <body ng-app="testApp" ng-controller="homeCtrl" ng-init="logged_in_user = {req.user}">
      <div...
      ...
    </body>

then you can access the logged_in_user in your homeCtrl, as "scope.logged_in_user" Hope this helps..

-Bhaskara



来源:https://stackoverflow.com/questions/16919942/angularjs-access-node-express-session-information

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!