使用Angular js的节点js RESTful API调用无效

时间:2016-04-29 09:42:26

标签: angularjs node.js api express

我使用节点js创建一个rest API来列出我的mongodb数据库值。但我无法通过角度js $ http方法访问该API。我没有任何想法。我是这些领域的新人。

我的节点表达api代码

app.get('/items', function(req, res, next) {

// query the data base to find all of the Items  
    Item.find({}, function(err, data){

// handle an error
        if (err) 
        {
            res.json(err);
        }
// handle an empty database by checking if the data array is empty
        else if (data.length===0) 
        {
            res.json({message: 'There are no items in the database.'});
        }
// if there are Items, return them  
        else 
        {

            //res.render('display',{ doc: data});
            res.json(data);
        }
    });
});

这是在node express中创建API的正确方法吗?

我使用以下angular js脚本调用API,但它总是显示错误。

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl"> 

<p>Today's welcome message is:</p>

<h1>{{myWelcome}}</h1>

</div>

<p>The $http service requests a page on the server, and the response is set as the value of the "myWelcome" variable.</p>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http({
    method : "GET",
    url : "http://127.0.0.1:8080/items"
  }).then(function mySucces(response) {
      $scope.myWelcome = response.data;
      alert("success");

    }, function myError(response) {
      $scope.myWelcome = response.statusText;
      alert("Some error occures...!");

  });
});
</script>

</body>
</html>

请任何人帮我解决这个问题。

但是我尝试了以下脚本成功运作,

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl"> 

<p>Today's welcome message is:</p>

<h1>{{myWelcome}}</h1>

</div>

<p>The $http service requests a page on the server, and the response is set as the value of the "myWelcome" variable.</p>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http({
    method : "GET",
    url : "http://api.worldweatheronline.com/free/v1/weather.ashx?q=London&format=json&num_of_days=5&key=atf6ya6bbz3v5u5q8um82pev"
  }).then(function mySucces(response) {
      $scope.myWelcome = response.data;


    }, function myError(response) {
      $scope.myWelcome = response.statusText;
  });
});
</script>

</body>
</html>

0 个答案:

没有答案