在nodejs / angularjs环境中不进行http查询

时间:2017-01-18 12:55:35

标签: javascript angularjs node.js httprequest

我正在创建一个使用angularjs与nodejs和mongoDB相结合的网站来处理登录和其他后端内容。我已经使用nodejs创建了API,可以通过发送到localhost:8080 / api或通过Postman发送HTTP-GET来成功测试它。但是,当我尝试使用angularjs代码进行HTTP-GET时,请求失败并返回一个空对象。

Warning once only: Detected a case where constraints ambiguously suggest a height of zero for a tableview cell's content view. We're considering the collapse unintentional and using standard height instead.

以下是我提出请求时浏览器控制台的图片:

enter image description here

我无法理解为什么API通过浏览器和Postman工作正常,但是当我尝试在代码中创建请求时失败。

--------------------------------- SOLUTION ------------- --------------------

我不得不在响应中添加一行代码来改变它:

Object { data: null, status: -1, headers: bd/<(d), config: Object, statusText: "" }

到此:

router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });   
});

---------------------------------- SOLUTION ------------ ------------------------

这是我的angularjs代码

router.get('/', function(req, res) {
    res.set('Access-Control-Allow-Origin', '*');    
    res.json({ message: 'hooray! welcome to our api!' });   
});

这是我的nodejs服务器代码

var mainApp = angular.module('mainApp', ['ngRoute']);

mainApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/frontpage', {
        templateUrl: 'public/views/frontpage.html',
        controller: 'frontpageController',
        activetab: 'frontpage'
    }).
      when('/login', {
        templateUrl: 'public/views/login.html',
        controller: 'loginController',
        activetab: 'login'
      }).
      otherwise({
        redirectTo: '/frontpage'
      });
}]);

mainApp.controller('mainController', function($scope, $route){
    $scope.$route=$route;
});

mainApp.controller('frontpageController', function($scope){
    $scope.test="frontpage";
});

mainApp.controller('loginController', function($scope, $http){
    $scope.rememberMe = false;
    $scope.submit = function(user){     
    $http({
        method: 'GET',
        url: 'http://localhost:8080/api'
        }).then(function successCallback(response) {
            console.log(response);
        }, function errorCallback(response) {
            console.log('dindu work');
            console.log(response);
        });
    };
});

1 个答案:

答案 0 :(得分:1)

如果您的网络应用和您的nodejs后端位于不同的网址上,请尝试以下操作:

10
data: 14 35 20


* transfer closed with outstanding read data remaining
* Closing connection 0
curl: (18) transfer closed with outstanding read data remaining