簡體   English   中英

如何將會話變量從express / node傳遞給angular?

[英]How to pass session variable from express/node to angular?

因此,基本上我使用的是角形路線,只是使用express來呈現索引頁面。

我想將會話變量從express傳遞到angular,但是我不知道如何在角度的每個路徑中獲取該變量。

app.js(express):

app.get('*', function (req, res) {
    res.sendFile(__dirname+'/client/views/index.html',{
        isAuthenticated:req.isAuthenticated(),
        user:req.user
    });
});

Index.html

<body>
<div class="main" ng-view>
    </div>
  </body>

Angular應用程序文件:

var myapp=angular.module('myApp', ['ngRoute','ngStorage']);
myapp.controller('contrl1', ['$scope' ,'$localStorage','$http', 
  function ($scope,  $localStorage,$http) {

  }]);
myapp.controller('contrl2', ['$scope' ,'$localStorage','$http', 
      function ($scope,  $localStorage,$http) {

      }]);
myapp.config(function($routeProvider, $locationProvider) {
  $routeProvider
   .when('/try', {
    templateUrl: '../views/view1.html',
    controller: 'contrl1',
  })
  .when('/hello', {
    templateUrl: '../views/view2.html',
    controller: 'contrl2',

  // configure html5 to get links working on jsfiddle
  $locationProvider.html5Mode(true);
});

所以基本上我想發送Isauthenticated變量和user變量,它們將具有會話值,從express到angular。我應該如何進行處理,以使這些值可以被angular中的所有路由訪問,以及如何在各個路徑中獲取這些值角度控制器。

    app.get('*', function (req, res) {
        res.sendFile(__dirname+'/client/views/index.html',{
            isAuthenticated:req.isAuthenticated(),
            user:req.user
        });
    });

真是個壞主意。 有更好的方法可以做到這一點。 這就是為什么您面臨問題共享的原因。 以下方法將起作用,請注意,我的解決方案僅是讓您開始如何做這種事情,使其變得安全,您可能必須重組您的angularjs應用程序,並在內部進行我正在做的事情ng-service或ng-factory,然后將它們注入控制器中。 這樣,您就可以訪問它。

考慮以下。

app.js

    var express = require('express');
    var path = require('path');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');

    var routes = require('./routes/index');

    var app = express();

    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'hbs');

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cookieParser());
    //This is very important, serve all your static files through public folder
    //Just inject your session variables to index.html, DO NOT PUT index.html
    //In you public folder, instead use index.hbs view as shown 

    app.use(express.static(path.join(__dirname, 'public')));

    app.use('/', routes);


    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
      var err = new Error('Not Found');
      err.status = 404;
      next(err);
    });

    // error handlers

    // development error handler
    // will print stacktrace
    if (app.get('env') === 'development') {
      app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
          message: err.message,
          error: err
        });
      });
    }

    // production error handler
    // no stacktraces leaked to user
    app.use(function(err, req, res, next) {
      res.status(err.status || 500);
      res.render('error', {
        message: err.message,
        error: {}
      });
    });


    module.exports = app;

./routes/index.js

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

    /* GET home page. */
    router.get('/', function(req, res, next) {
      res.render('index', {
        title: 'Pass session vairabled to my hbs',
        isAuthenticated: true,
        user: JSON.stringify({id: 2, name: 'dummy'})
      });
    });

    module.exports = router;

./views/layout.hbs

    <!DOCTYPE html>
    <html>
      <head>
        <title>{{title}}</title>
        <link rel='stylesheet' href='/stylesheets/style.css' />
      </head>
      <body>
        {{{body}}}

        <!-- References of Angular.js and all your other angular files and services go here -->
        <script>
           var isAuthenticated= {{isAuthenticated}};
           var user = {{{user}}};
        </script>
      </body>
    </html>

./views/index.hbs

    <h1>{{title}}</h1>

    <div class="main" ng-view>
    </div>

以下是快照-概念證明。

在此處輸入圖片說明

現在在這里,我剛剛將變量注入普通的公共js變量中,您需要編寫ng-service / ng-factory進行封裝。

以下是我建議的結構

    .
    ├── LICENSE
    ├── README.md
    ├── app.js
    ├── bin
    │   └── www
    ├── package.json
    ├── public
    │   ├── images
    │   ├── javascripts
    │   ├── views
    │   │   └── <angular view templates>
    │   └── stylesheets
    │       └── style.css
    ├── routes
    │   └── index.js
    │   
    └── views
        ├── error.hbs
        ├── index.hbs //Your actual index file, this will contain ng-view
        └── layout.hbs

希望這可以幫助!! 如果可以給我進一步的幫助,請告訴我。

我不認為這是可能的。

即使使用sendFile ,只要設置了view engine ,您仍然可以在文件中使用任何類型的模板化內容。


您可以將其存儲在一個可能隱藏的元素中,然后僅使用js從中獲取信息,或者我認為angular在控制器加載后使用諸如服務之類的東西來加載此類數據

<input type="hidden" id="auth" value="#{authenticated}"/>

然后,一旦控制器加載,就使用JavaScript獲取值

但是,這是駭人聽聞的,並不是真正的做事方式。 我很確定您應該為此使用服務。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM