我有一個函數,它通過進行API調用來列出附加到SQL服務器的數據庫。
function dbList(resource, args, scope, server){
// Recieves a list of DBs from the API and adds it to the scope
scope.loadingResponse = true;
resource('http://localhost:1000/apiv1/servers/:server/databases',
{server: server}).get(args).$promise.then(function (result) {
scope.databases = result.databases;
scope.loadingResponse = false;
}, function(error){
console.log(JSON.stringify(error));
errorHandler(scope, error)
})
}
它是從我的控制器喜歡叫:
dbList($resource, args, $scope, 'SERVER1');
它傳遞遇到我的錯誤處理程序的任何錯誤,評估它們:
function errorHandler(scope, error){
// Displays the error message and ends the loading animation
var err_code = error.status;
var err_message = 'Error Code ' + error.status + ': ';
console.log(JSON.stringify(error))
if (err_code == 401){
err_message += 'Unauthorized. Cookie expired or nonexistent.';
}
else if (err_code == 400) {
err_message += 'Missing parameter. Ensure all necessary fields are filled'
}
else if (err_code == 404) {
err_message += 'Resource not found. Ensure that it exists.'
}
else if (err_code == 405) {
err_message += 'Method not allowed. This could be caused by XHR Cross Domain Option requests.'
}
else if (err_code == 409) {
err_message += 'The Resource you wish to use is in use. Ensure that there is no name conflict with an attached database.'
}
scope.loadingResponse = false;
scope.error = err_message;
}
我撥打電話到API而無需提交我必須驗證的令牌,並根據Firefox控制檯獲取401錯誤。這是在沒有令牌的情況下訪問API時的預期行爲。所以我預計$ scope.error設置爲Error Code 401: Unauthorized. Cookie expired or nonexistent.
然而,我所得到的是Error Code 404: Resource not found. Ensure that it exists.
Firefox的控制檯上寫着:
[13:39:20.419] GET http://localhost:1000/apiv1/servers? [HTTP/1.0 401 UNAUTHORIZED 5ms]
[13:39:20.413] "{"data":"","status":404,"config":{"transformRequest":[null],"transformResponse":[null],"method":"GET","url":"http://localhost:1000/apiv1/servers","params":{},"headers":{}}}"
如何以及爲什麼angular.js改變了我401到404,我怎樣才能訪問正確的狀態碼?
ETA: 問題原來是由我用來運行的Flask API導致的跨域請求問題。在下面看到我的回答
angularjs不會將401轉換爲404從服務器端檢查您的請求。另外,請檢查瀏覽器網絡選項卡的響應。 – allenhwkim
兩者都說401,就像Firefox控制檯一樣。 –
其他瀏覽器對狀態代碼的評價是什麼? –