簡體   English   中英

如何從 URL 獲取狀態代碼

[英]How to get status code from URL

你好,我是 javascript 和 AngularJS 的新手。這是我從服務器獲取 .json 的函數(服務器返回一個 JSON):

function getProducts() {
        return $http.get(urlProducts).then(
            //Success
            function(response) {
                products= response.data.result;
                return products;
             },
            //Error
            function(response) {
                //put best way to return an error
                return something;
            }
        );
    }

我的問題是:這是從 Web 服務器獲取數據的最佳方式我不僅想知道響應是否成功,還想知道狀態代碼是否為 200。

然后我想知道是否是我真正想要返回的錯誤(我想顯示帶有文本的圖像:“無法與服務器連接。再試一次”)。 但我使用 Ionic(HTML5、CSS3 和 javascript 與 AngularJS)制作應用程序。 那么......返回錯誤的最佳方法是什么,我想顯示一個帶有文本的圖像,該圖像是關於我在 apache cordova 中編程的。 謝謝!

根據 AngularJS 文檔:

$http 服務是一個核心的 Angular 服務,它促進與遠程 HTTP 服務器的通信

來自 $http 調用的響應對象具有以下屬性(除其他外):

data – {string|Object} – 使用轉換函數轉換的響應主體。

status – {number} – 響應的 HTTP 狀態代碼。 您可以使用它來制定基於不同代碼的邏輯

statusText – {string} – 響應的 HTTP 狀態文本。

在您的示例中,您已經實現了 Promise.protorype.then() 函數,該函數允許您委托成功(第一個參數)和錯誤(第二個參數)在承諾完成后進行進一步處理($http.get 調用已完成) )。

根據您的示例,我將這樣做:

function getProducts() {
    // Call the http get function
    return $http.get(url).then(

        //The request succeeded - 200 status code
        function(response) {
            products= response.data.result;
                return products;
        },

        //The request failed
        function(response) {

           // Here you can access the status property and the statusText
           console.log("Http Status: " + response.status + " Description: " +   response.statusText);

           // Return a false result
           return false;
});

我通常會使用像Angular-UI-Notification這樣的庫並清理它,我像這樣實現它:

//The success handler function
function handle_response_success(response) {
    // Do processing here based on the response then show a success notification
    Notification.success('Success notification');
};

// The error handler function
function handle_response_error(error) {
     Notification.error('Something went wrong with that request. More Info: ' + 'Http Status: ' + error.status + ' Description: ' +   error.statusText);
}

// Then finally bind it to your getProducts call

function getProducts() {

    // More elegant proto imho
    return $http({ method: 'GET',
        url: 'http://example.com'
     });
};

// More elegant way to handle this imho
getProducts.then(handle_response_success.bind(this), handle_response_error.bind(this);

暫無
暫無

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

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