2012-10-25 58 views
3

我試圖使用「Amplifyjs」來處理AJAX請求,就像約翰帕帕在他的Pluralsight課程中一樣,但我遇到了身份驗證問題。Amplifyjs和狀態代碼

我正在使用表單身份驗證。一切正常。

我的問題伴隨着未經驗證的請求。我無法找到一種方法讓「amplifyjs」返回錯誤函數的http代碼(401,403 ...),以區分由於未通過因未滿足業務邏輯而失敗的請求進行身份驗證而失敗的請求。

請求的例子是:

amplify.request.define("products", "ajax", { 
       url: "/api/Products", 
       datatype: "json", 
       type: "GET" 
      }); 
amplify.request({ 
        resourceId: "products", 
        success: callbacks.success, 
        error: function (datos, status) { 
           //somecode 
          } 
       }); 

謝謝。

回答

6

如果您想要XHR對象並將其傳遞,您可以創建一個解碼器。它將有您可能需要的錯誤代碼和其他信息。

amplify.request.define("products", "ajax", { 
    url: "http://httpstat.us/401", 
    datatype: "json", 
    type: "GET", 
    decoder: function (data, status, xhr, success, error) { 
     if (status === "success") { 
      success(data, xhr); 
     } else if (status === "fail" || status === "error") { 
      error(status, xhr); 
     } else { 
      error(status, xhr); 
     } 
    } 
}); 

amplify.request({ 
    resourceId: "products", 
    success: function(data, status) { 
     console.log(data, status);   
    }, 
    error: function(status, xhr) { 
     console.log(status, xhr); 
    } 
});​ 

您可以通過查看該http://jsfiddle.net/fWkhM/

+0

對不起,我將發表評論作爲新的答案。我無法在評論中正確設置文本的格式(或者我不知道如何) –

+0

@Elijah Manor,您能否提供有關如何讓xhr值回到成功回調的工作解決方案?我創建了一個自定義解碼器,但成功回調似乎總是被默認覆蓋。謝謝 – stvn

+0

如果你把它放在足夠多的電話上,它似乎會中斷,這會消耗它應該給的用途。對於爲什麼我們只得到默認的「成功」或「錯誤」,我確實感到困惑。 – Nickvda

2

謝謝您的回答測試上面的代碼。

最後,我認爲沒有人回答我,我沒有類似的東西給你提出什麼:

var decoder = function (data, status, xhr, success, error) { 
    if (status === "success") { 
     success(data, status); 
    } else if (status === "fail" || status === "error") { 
     try { 
      if (xhr.status === 401) { 
       status = "NotAuthorized"; 
      } 
      error(JSON.parse(xhr.responseText), status); 
     } catch (er) { 
      error(xhr.responseText, status); 
     } 
    } 
}; 

後,我修改默認解碼器:

amplify.request.decoders._default = decoders.HeladeriaDecoder; 

,並在錯誤回調我管理返回的狀態。

error: function (response, status) { 
    if (status === "NotAuthorized") { 
     logger.error(config.toasts.errorNotAuthenticated); 
    } else { 
     logger.error(config.toasts.errorSavingData); 
    } 
//more code... 
}