Sajak Upadhyaya
Sajak Upadhyaya

Reputation: 401

Unexpected token 'u' in NodeJS

I am making a ticketing system where I collect the index of the seats in array but when collecting with Node it is collected as an Object which I parse using JSON.parse.

Here's the code from the controller of my Angular Controller

  $scope.bookThisSeat = function(seatIndex){

    console.log(seatIndex);
    $scope.ticket.selectedSeats.push(seatIndex);
    console.log($scope.ticket)
  }

  $scope.registerTicket = function(){
    $scope.ticket.selectedBus = $scope.ticket.selectedBus.id;
    $scope.ticket.selectedSeats = angular.toJson($scope.ticket.selectedSeats);
    console.log($scope.ticket);
    $http.post('/tickets/create',$scope.ticket).
    success(function(data){
      if(data.success){
        console.log("success")
      }

    }).
    error(function(err){
      console.log(err);
    })
  }

And here's my node JS function to collect the input data

  collect: function(req,res,next){
    var fields = ['id','departure','destination','depDate','desDate','selectedSeats','amount','passenger_name','phone','selectedBus'];
    var reqdata = {};
    fields.forEach(function(entry){
      if(typeof req.body[entry] !=='undefined')
        reqdata[entry] = sanitize(req.body[entry]);
      if(typeof req.query[entry]!== 'undefined')
        reqdata[entry] = sanitize(req.query[entry]);
      if(typeof req.params[entry] !== 'undefined')
        reqdata[entry] = sanitize(req.params[entry]);
    });
    reqdata.selectedSeats = JSON.parse(reqdata.selectedSeats);
    req.saf_tktdata = reqdata;

It works fine when I am collecting all the data, but it returns an Unexpected error u whenever I want to only collect the depDate or desDate fields.

How can I solve this?

Upvotes: 0

Views: 321

Answers (1)

Even
Even

Reputation: 238

I guess "Unexpected error u", the u in that error log means undefined

when you collect all the data, reqdata.selectedSeates is not undefined

but when you collect depDate or desDate only, probably reqdata.selectedSeates is undefinded and it cannot be JSON.parse

so a quick fix is

reqdata.selectedSeats = reqdata.selectedSeats ? JSON.parse(reqdata.selectedSeats) : null;

Upvotes: 1

Related Questions