简体   繁体   中英

Angular HTTP GET request returns undefined while working in browser

I'am learning AngularJs and I've tried to write a very basic script sending an http request to Ebay public API, I've signed up and got my API keys, I've read the docs several times and wrote this basic code :

 $scope.getQueryUrl = function () {
    // Some unrelated code ...
    $scope.queryUrl["Ebay"] = "http://svcs.sandbox.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findItemsByKeywords&SERVICE-NAME=FindingService&SERVICE-VERSION=1.0.0&GLOBAL-ID=EBAY-US&SECURITY-APPNAME="+dataAuth.EbayKeyApi+"&RESPONSE-DATA-FORMAT=XML&keywords="+$scope.qtext ;

};
$scope.sendRequest = function () {

    $scope.getQueryUrl(); // Gets the query url after adding all the parameters
    alert($scope.queryUrl.Ebay);
    $http.get($scope.queryUrl["Ebay"]).then(
        function(response){
            alert("success" + response.data );
        },
        function(response){
            alert("error"   + response.statusCode );
        });


};

How this code should work :

It should create a formated Ebay query url, send it through HTTP GET request and sending back the response .

Note : $scope.qtext & dataAuth.EbayKeyApi are already assigned with their respective values .

What's the problem :

The problem is that using this Angularjs script, the code doesn't work, the alert "Error" is shown, and the response.statusCode is undefined .

But when I copy the formatted Ebay query link in Firefox it works perfectly and the XML response is shown .

The formatted Ebay query was generated using the script provided .

I think it's a header related problem .

$http has some default headers defined. $http sends Json payload and accepts Json as the response by default. Since you are dealing with XML you have to explicitly specify the accepted response type as XML using the header: Accept: application/xml

Please use the following function with appropriate headers and you should get the response. Also, please look into any Cross Origin Resource Sharing (CORS) restrictions on the ebay API.

    function getRequest(url) {

        $http({
            method: "GET",
            url: url,
            headers: {
                'Content-Type': 'application/xml, text/xml',
                'Accept': 'application/xml, text/plain, * / *'
            }
        })
            .then(function (response) {
                    alert(response.data);
                },
                function (error) {
                    alert (error);
                });
      }

Thank you, Soma.

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