简体   繁体   中英

AngularJS API call error with $http GET

I'm trying to create a simple app using Angular that will consume my API. I'm using a VM to run the code, and I access it on my computer, so to call the API from my machine I can use cURL or any other HTTP client and everything works. An example:

curl -k --user damien@email.com:password https://api.my.domain.com/v1/traveler/get

And that would return a list of travelers for example. I need to "trust" the certificate as it is not valid. So on the browser at first the call would return net::ERR_INSECURE_RESPONSE , so I'm just going to the API URL and add the exception and now I don't have this issue anymore. Then I had to add basic authentication, and it seems to work. Let's see what is my code and please let me know if you see anything wrong, I'm following this tutorial that consume an external API: http://www.toptal.com/angular-js/a-step-by-step-guide-to-your-first-angularjs-app

app.js:

angular.module('TravelerApp', [
    'TravelerApp.controllers',
    'TravelerApp.services'
]);

services.js:

angular.module('TravelerApp.services', [])
.factory('TravelerAPIService', function($http) {
    var travelerAPI = {};

    $http.defaults.headers.common.Authorization = 'Basic ABC743HFEd...=';

    travelerAPI.getTravelers = function() {
        return $http({
            method: 'GET',
            url: 'https://api.my.domain.com/v1/traveler/get'
        });
    }

    return travelerAPI;
});

Finally, the controllers.js:

angular.module('TravelerApp.controllers', [])
.controller('travelersController', function($scope, TravelerAPIService) {
    $scope.travelersList = [];

    TravelerAPIService.getTravelers()
    .success(function(data) {
        console.log('SUCCESS');
        $scope.travelersList = data;
    })
    .error(function(data, status) {
        console.log('ERROR');
        $scope.data = data || "Request failed";
        $scope.status = status;
    });
});

The error status code is 0, and the error data is an empty string.

Precisions:

I have the same behavior with an HTTP POST query. I am sure :

  • no request have been made on the server
  • it's angular that don't sent the query

And finally I find the answer:

Since I (and probably you) are sending on a self signed httpS server. Chrome flag it as none safe.

I fix this issue by putting the address on my browser and manually accept the certificate.

Probably related : XMLHttpRequest to a HTTPS URL with a self-signed certificate

我建议使用Trusted CA Signed SSL证书,而不要使用Self-Signed证书,因为大多数浏览器都不接受Google Chrome,Firefox等自签名证书,因此可以解决您的问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM