0

//index.js where i start my session

  exports.index = function(req, res){

req.session.username = "sachin";
console.log(req.session.username);
if(req.session.username)
    {
console.log("Sessssion initialized");
    }
res.render('index', { title: 'Express' });

};
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
 });

//app.js

/** * Module dependencies. */

 var express = require('express')
 , routes = require('./routes')
 , user = require('./routes/user')
 , http = require('http')
 , path = require('path')
 , session = require('client-sessions');


 var app = express();
 app.use(session({   

 cookieName: 'session',    
 secret: 'cmpe273_test_string', 
  saveUninitialized: true, // (default: true)
    resave: true, 
    duration: 30 * 60 * 1000,    
    activeDuration: 5 * 60 * 1000,  }));

 app.configure(function(){
 app.set('port', process.env.PORT || 3070);
 app.set('views', __dirname + '/views');
 app.set('view engine', 'ejs');
 app.use(express.favicon());
 app.use(express.logger('dev'));
 app.use(express.bodyParser());
 app.use(express.methodOverride());
 app.use(app.router);
 app.use(express.static(path.join(__dirname, 'public')));
 app.use(express.static(path.join(__dirname, 'routes')));
 });

 app.configure('development', function(){
  app.use(express.errorHandler());
  });

  app.get('/', routes.index);

//orders.ejs////////////

   <h3>Menu</h3>

   <table class="table table-striped">
  <thead><tr>
  <th>Item Number</th>
  <th>Item Name</th>
  <th>Price</th>
  </tr></thead>
  <tbody><tr ng-repeat="item in items" >
  <td>{{$index + 1}}</td>
  <td>{{ item.Name }}</td>
  <td>{{ item.price }}</td>
  <td><input type="radio" name={{$index}} ng-click="cal(item.id)"<br>       </td>
  </tr></tbody>
 </table>

  <button class="btn" ng-click="res()">
    <span class="glyphicon glyphicon-pencil"></span>Submit
  </button>

//order.js

/**

* New node file */

   var app = angular.module('myApp', []);
   angular.module('myApp', []).controller('orderCtrl', function($scope)    {
    var json_responses
    $scope.name = '';
    $scope.price = '';
    $scope.total=0;
    $scope.output=0;
    $scope.fina = [];
    $scope.finals=[];
    $scope.items = [
    {id:1, Name:'Garlic Bread',price:20 },
    {id:2, Name:'Butter Chicken',price:30 },
    {id:3, Name:'Tandoori Chicken',price:25 },
    {id:4, Name:'Naan',price:5},
    {id:5, Name:'Ice Cream',price:10},
    {id:6, Name:'Pizza',price:15 }
    ];
    $scope.cal=function(id){
         $scope.output = $scope.output+$scope.items[id-1].price;
         $scope.fina.push({id:$scope.items[id-1], Name:$scope.items[id-     1].Name,price:$scope.items[id-1].price}); 

    }


    $scope.res=function(fina){
        $scope.total= $scope.output;
        $scope.finals=angular.copy($scope.fina);
    }
  });

When i select the buttons and submit and get the bill and then refresh the page all the data is lost. How do i get the data to stay even after refreshing?? Please help me out.

sachin hunur
  • 281
  • 2
  • 6
  • 17

1 Answers1

0

You're using client-sessions to store state in the user's cookies but you're not actually storing the order details. You'll need to add another route to take the data and add it to the req.session object in the same way as you have with username. First you'll need to add the body-parser dependency by running npm install body-parser --save.

var bodyParser = require('body-parser');

//Use body-parser middleware to populate req.body from POST json data
app.use(bodyParser.json());
app.post('/submit', function (req, res){
  //TODO check that the data is valid before just using it
  req.session.order = req.body.order;
  res.redirect('/');
});

You need to modify the angular controller to post the data when calling res():

angular.module('myApp', ['$scope', '$http']).controller('orderCtrl', function($scope, $http) {
  /* Existing code */
  $scope.res=function() {
    $scope.total= $scope.output;
    $scope.finals=angular.copy($scope.fina);
    $http.post('/submit', {order: $scope.finals});
  }
}

In general you're best using angular forms rather than doing it yourself with just a controller as they give you two-way data-binding but it can be instructive to learn it without the magic first.

piemonkey
  • 741
  • 3
  • 6
  • This is the first time i am implementing sessions. So when you say get data from request exactly how do i get the data i.e. the selected values and output? – sachin hunur Oct 05 '15 at 10:10
  • That depends how you send it. I'll update the answer to send JSON as a POST. – piemonkey Oct 05 '15 at 11:17
  • Thanks a lot for the help. But when i edited the code as given above i got this error while debugging Error: $injector:modulerr Module Error. Failed to instantiate module myApp. Any idea about that? – sachin hunur Oct 05 '15 at 11:56
  • i changed the code to angular.module('myApp', [ ]).controller('orderCtrl', function($scope, $http) instead of angular.module('myApp', ['$scope', '$http']).controller('orderCtrl', function($scope, $http) and the error went . But now it says http://localhost:3070/submit not found. – sachin hunur Oct 05 '15 at 12:03
  • The res.redirect('/'); command keeps send the control back to the same page with all the data refreshed. Not able to retain the data. – sachin hunur Oct 05 '15 at 12:29
  • Oops, I used app.get instead of app.post, so it was saying that it couldn't find what to do with a POST to /submit – piemonkey Oct 05 '15 at 13:36
  • The module error you're seeing is most likely because you're calling `angular.module()` twice. The first time you call it for a module (in your case 'myApp') you need to define the dependencies, which is what the array argument is. It should work with just the line I've given and removing your call to `angular.module('myApp', [])`. – piemonkey Oct 05 '15 at 13:44
  • Also, I notice now that you're not actually displaying the order anywhere in the code above. You'll need to put something into your orders.ejs file to display the data. See https://stackoverflow.com/questions/25248394/how-do-i-pass-node-js-server-variables-into-my-angular-html-view for more details. – piemonkey Oct 05 '15 at 14:06