RESTful API not showing up with simple AngularJS controller

时间:2016-07-11 23:02:04

标签: javascript mysql angularjs api rest

Alright, I'll try and explain this as simply as possible. I have setup a Node and express and mySQL server running a RESTful API with the common get, post, put, delete working fine as I can test them with them in Postman and just looking it up in Chrome. This is all run locally on my machines for now. I have a Ubuntu box running the REST api. When I just query in chrome I get an expected output of the fields I am working with.

(Example request "http://192.168.239.130:1337/api/plates/") Gives me this.

{
"Plates": [
    {
        "lot_number": "P234",
        "plate_number": "NGE-781",
        "date_and_time": "2016-07-08T21:14:31.000Z"
    },
    {
        "lot_number": "P234",
        "plate_number": "FEB-423",
        "date_and_time": "2016-07-08T21:26:08.000Z"
    },
    {
        "lot_number": "P234",
        "plate_number": "SEB-623",
        "date_and_time": "2016-07-08T21:26:20.000Z"
    },
    {
        "lot_number": "P234",
        "plate_number": "ZEB-683",
        "date_and_time": "2016-07-08T21:30:59.000Z"
    },
    {
        "lot_number": "P234",
        "plate_number": "FEW-083",
        "date_and_time": "2016-07-08T21:31:57.000Z"
    },
    {
        "lot_number": "L323",
        "plate_number": "JEQ-324",
        "date_and_time": "2016-07-11T18:59:03.000Z"
    }
   ]
 }

These are just some sample mySQL data that is printed to screen. Which is working as I had hoped. My problem is when I try to make a simple html page with angular script to try and print it it doesn't want to. All I get is a blank page. I have tried running my code with other api's online. I have no problem printing those out with the identical code which I will post below.

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

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

{{plates}}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('platesCtrl', function($scope, $http) {
   $http.get("http://192.168.239.130:1337/api/plates")
   .then(function (response) {$scope.plates = response.data;});
});
</script>

</body>
</html>

Like I said running this with any other API online works.... Mine doesn't It it something that has to do with it be local? Even though like I stated I can run the above address to the ....api/plates API in a browser no problem and get the JSON to spit out.

Any knowledge would be appreciated

Thanks.

1 个答案:

答案 0 :(得分:0)

好吧,我自己也会回答这个问题。从其他一些用户的评论中思考。我检查了控制台,并且发出了一个错误消息,指出我有一个跨域问题,并且“访问控制 - 允许 - 来源”#39;失踪。我能够修复进入我的API调用函数并添加

res.header("Access-Control-Allow-Origin", "*");

每个API调用。现在,虽然我确信有一种更优雅的方式来实现同样的东西,但这是有效的。

感谢您的帮助。