【问题标题】:using express angularJs and mongoDB but ngResource in angular not loading使用 express angularJs 和 mongoDB 但 ngResource 在 Angular 中未加载
【发布时间】:2013-09-13 15:17:04
【问题描述】:

这是我的 MongoDB 后端代码

 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);

                  }
             });

          });
      });
   }

这是我的 Node.js 快速代码

   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'));
    });

这是我的 angularJs app.js 代码

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();

 }

这里是 index.html 文件

   <!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>

这是我的 list.html 文件

 <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>

list.html 模板正在加载。我收到错误 Failed to load resource: the server respond with a status of 500 (Internal Server Error) ?我也收到错误错误:发送后无法设置标题。我可以在控制台中以列表方法注销数据。任何帮助将是非常可观的?

【问题讨论】:

  • 每当您在 Web 服务上遇到 500 错误时,您需要获取该 POST 或 GET 并在命令行中使用 cURL 运行它。隔离始终是故障排除的第一步。
  • 我使用 cURl 127.0.0.1:3000 我得到了 index.html 文件,但是当我使用 cURl 127.0.0.1:3000/api/cars 时,我得到了同样的错误

标签: javascript node.js mongodb angularjs express


【解决方案1】:

您的问题在 cars.list 函数内部。

Express 路由的结构如下function myRoute(req, res, next) {...}
next 函数(或您所说的 callback)只有在中间件之后有另一个函数时才有用。
也许之后会调用errorHandler 中间件(app.get('/api/cars', cars.list);),我不确定。

问题可能是您调用callback(true) 来启动下一个中间件(并使用headers 等发送响应),然后尝试使用res.json(...) 发送另一个响应。
你需要删除callback(true)

所以我认为你应该这样重写你的函数:

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);
        }
      });
    });
  });
}

【讨论】:

    猜你喜欢
    • 2014-07-14
    • 1970-01-01
    • 2015-05-28
    • 2013-09-20
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    相关资源
    最近更新 更多