具有Angular的NodeJs API不返回JSON结果

时间:2016-05-24 05:38:56

标签: angularjs json node.js api cors

更新:我尝试了其他API:http://www.omdbapi.com/?t=Sherlock

GET有效。但是,我仍然不确定为什么我的node.js服务器API无法使用此方法。

我目前正在处理一个应用程序的后端,我创建了一个类似于教程的API:https://codeforgeek.com/2015/03/restful-api-node-and-express-4/

然而,我似乎无法获得我的离子角应用程序来检索我的JSON结果。当我把我的get命令放在Postman上时,我得到:

[{"floor":3}]

我的控制器是:

   $http({url:"http://localhost:3000/api/fl",method:'GET'})
    .then(function(response) {
          $scope.status = response.status;
          $scope.data = response.data;
          $log.log("success");
          $log.log("res:"+ response);
        }, function(response) {
          $scope.data = response.data || "Request failed";
          $scope.status = response.status;
          $log.log("failed");
          $log.log("res:"+ response);
      });

 $log.log("status: "+$scope.status); 
 $log.log("data: "+$scope.data);

(我的/ fr引用了我的节点服务器上有GET方法的JSON)

总是给出结果"失败","状态:未定义"以及"数据:undefined"。当我推算这种方法时,它会给我一个"状态:0"。

我也试过使用$ resource但没有成功。 任何指导将不胜感激。我的API没有任何身份验证,我也不认为它与CORS有任何关系(除非你们认为这样做)。

修改 这是我的server.js上的get方法:

//GET Floor
 router.get("/fl",function(req,res){
        var query = "SELECT floor FROM stor1 WHERE id=0";

        connection.query(query,function(err,rows){
            if(err) {
                res.json({"Error" : true, "Message" : "Error executing MySQL query"});
            } else {
                res.json(rows);
            }
        });
    });

EDIT2: 好吧,我添加了更多日志来显示结果,现在我从响应中获得了[object Object]。对象是: {"data":null,"status":0,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"http://localhost:3000/api/fl","headers":{"Accept":"application/json, text/plain,*/*"}},"statusText":""}

3 个答案:

答案 0 :(得分:1)

您的邮递员似乎得到GET请求的响应,这意味着您的服务器端代码可以正常路由。但是你的Angular App无法在服务器端抛出任何错误而得到任何响应。这似乎是 CORS

的情况
var cors = require('cors');    
app.use(cors());

注意:在第一条路线之前使用此中间件。

答案 1 :(得分:1)

还有一种方法可以 Access-Control-Allow-Origin

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
});

答案 2 :(得分:0)

尝试为成功和错误回调函数添加名称,如下所示:

$http({url:"http://localhost:3000/api/fl",method:'GET'})
.then(function successCallBack(response) { // Add 'successCallBack' function name
      $scope.status = response.status;
      $scope.data = response.data;
      $log.log("success");
      $log.log("res:"+ response);
    }, function errorCallBack(response) { // Add 'errorCallBack' function name
      $scope.data = response.data || "Request failed";
      $scope.status = response.status;
      $log.log("failed");
      $log.log("res:"+ response);
  });

$log.log("status: "+$scope.status); 
$log.log("data: "+$scope.data);