簡體   English   中英

在瀏覽器中工作時,Angular HTTP GET請求返回未定義

[英]Angular HTTP GET request returns undefined while working in browser

我正在學習AngularJs,並且嘗試編寫一個非常基本的腳本來向Ebay公共API發送一個http請求,我已經注冊並獲得了我的API密鑰,我已經閱讀了幾次文檔並編寫了這個基本代碼:

 $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 );
        });


};

此代碼應如何工作:

它應該創建一個格式化的Ebay查詢URL,通過HTTP GET請求將其發送並發送回響應。

注意: $scope.qtextdataAuth.EbayKeyApi已經分配了各自的值。

有什么問題

問題在於,使用此Angularjs腳本,代碼不起作用,顯示警告“錯誤”,並且response.statusCode未定義。

但是,當我在Firefox中復制格式化的Ebay查詢鏈接時,它可以正常工作並顯示XML響應。

格式化的Ebay查詢是使用提供的腳本生成的。

我認為這是與標頭相關的問題。

$ http定義了一些默認標題。 $ http默認發送Json有效負載並接受Json作為響應。 由於您正在處理XML,因此必須使用標頭將接受的響應類型明確指定為XML:Accept:application / xml

請使用以下帶有適當標題的函數,您應該會得到響應。 另外,請查看eBay API上的任何跨源資源共享(CORS)限制。

    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);
                });
      }

謝謝你索瑪

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM