1

Here Is my MongoDB backend code

 var mongo = require("mongodb");
 var DbHost = "127.0.0.1";
 var DbPort = mongo.Connection.DEFAULT_PORT;


  module.exports.list = list;

  var db = new mongo.Db("ferrari-db",new mongo.Server(DbHost,DbPort,{}),{safe:true});
  var collectionName  = "carsList";


  function list(req,res,callback){

     db.open(function(error){
        db.collection(collectionName,function(error,collection){
           console.log("have the collection");
           collection.find().toArray(function(error,data){
               if (error) callback(false);
                else{
                   callback(true);
                   console.log(data);
                   res.json(data);

                  }
             });

          });
      });
   }

Here is my Node.js express code

   var express = require('express');
   var http = require('http');
   var path = require('path');
   var cars = require('./server/api/cars.js')

   var app = express();

   var client_dir =  path.join(__dirname, '/client')
   // all environments
   app.set('port', process.env.PORT || 3000);
   app.use(express.favicon());
   app.use(express.logger('dev'));
   app.use(express.bodyParser());
   app.use(app.router);
   app.use(express.static(client_dir));


   // development only
   if ('development' == app.get('env')) {
        app.use(express.errorHandler());
    }

   app.get('/', function(req,res){
       res.sendfile(path.join(client_dir,'index.html'))

    });

    app.get('/api/cars',cars.list);

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

Here is my angularJs app.js code

var CarApp = angular.module('CarApp',['ngResource'])

CarApp.config(function($routeProvider){
    $routeProvider
        .when('/',{controller:ListCtrl,templateUrl:'partials/list.html'})
         .otherwise({redirectTo:'/'})

 }) ;

 CarApp.factory('Cars',function($resource){
      return $resource('/api/cars/:id',{id:'@id'},{update:{method:'PUT'}})
 });

 function ListCtrl ($scope,Cars){

     $scope.cars = Cars.query();

 }

Here is index.html file

   <!DOCTYPE html>
  <html>
  <meta charset="utf-8">
  <title>Ferrari</title>


 <link type="text/css" rel= "stylesheet" href="vendor/bootstrap/css/bootstrap.css"/>
 <script src="vendor/bootstrap/js/bootstrap.js"></script>
 <script src="vendor/angular.min.js"></script>
 <script src="vendor/angular-resource.min.js"></script>
 <script src="js/app.js"></script>

 <body>
 <h1>Hello</h1>

      <div ng-app="CarApp" class="container">
           <div ng-view>
            </div>
      </div>
  </body>

  </html>

here is my list.html file

 <table class= "table table-bordered table-hover">
  <thead>
      <th>Type</th>
      <th>Mileage</th>
      <th>Year</th>
      <th>Price</th>
  </thead>

<tr ng-repeat="car in cars">
    <td>{{ car.title }}</td>
    <td>{{ car.mileage }}</td>
    <td>{{ car.year }}</td>
    <td>{{ car.price }}</td>
</tr>

</table>

The list.html template is loading . I get the error Failed to load resource: the server responded with a status of 500 (Internal Server Error) ? Also i get the error Error: Can't set headers after they are sent. I can log out the data in console in list method. Any help would be highly appreciable?

2
  • anytime you hit a 500 error on a web service you need to grab that POST or GET and run it at the command line with cURL. Isolation is always the first step in troubleshooting. Commented Sep 13, 2013 at 16:18
  • i use cURl 127.0.0.1:3000 i get the index.html file but when i do cURl 127.0.0.1:3000/api/cars i get the same error Commented Sep 13, 2013 at 17:06

1 Answer 1

1

Your issue is inside the cars.list function.

The structure for an Express route is the following function myRoute(req, res, next) {...}.
The next function (or callback as you put it) is only useful if you have another function after in the middleware.
Maybe the errorHandler middleware is called afterwards (app.get('/api/cars', cars.list);), I'm not sure about that.

The problem might be that you call callback(true) which launches the next middleware (and sends a response, with headers, etc.), and then tries to send another response with res.json(...).
You need to drop callback(true).

So I think you should rewrite your function like that:

function list(req, res, next) {

  db.open(function (error) {
    db.collection(collectionName, function (error, collection) {
      console.log('Have the collection');
      collection.find().toArray(function(error,data){
        if (error) {
          // Hopefully we pass the error to the error handler
          return next(error);
        } else {
          // If everything goes fine we send the data.
          console.log(data);
          return res.json(data);
        }
      });
    });
  });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.