AngularJS - Access node / express session information

I am working on a node application that uses Express and Passport for authentication and authorization, and it all works correctly. However, I am at a dead end on how to get the current user (set as req.user by Passport) in my Angular controllers.

I want to be able to do the usual things, such as displaying the username in the title / navigation bar (by the way), and currently I am doing this using the Jade view mechanism, but I don’t like mixing using Jade to view the mechanism for some 'bindings data and Angular for others.

Now I know that I could easily make an api endpoint call to node that returns req.user as JSON, but this seems like an ugly solution, as I would hit that endpoint every time there is (this is not SPA )

So, my question basically consists in the following: can I get a registered user in my Angular views so that I can execute all my client side, data binding, instead of any server part (with Jade view engine) and some client side with Angular?

Note. There are no code snippets, because everything actually works as intended, I just hope for a better alternative than what I have.

+4
source share
1 answer

Consider using "ng-init" in the DOM, which defines an ng application, that is, server-side data printed in Express (assume the Dust pattern). The following is a simple example:

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

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

-Bhaskara

+1
source

Source: https://habr.com/ru/post/1484420/


All Articles