在發出HTTP請求之前,我需要檢查我擁有的訪問憑證是否有效。如果它們無效,我需要發出第一個HTTP請求來重新驗證它們,然後在完成之後再發出第二個HTTP請求(原始請求)。函數調用需要從第二個HTTP請求返回Angular的$http
承諾。這裏是我的功能:鏈2 HTTP請求並返回第二個承諾
var makeRequest = function (scope, address, request, basic, form) {
startLoad(scope);
// Check if user is logged in and needs a new session token...
if (ready() && (now() > getSessionExpires()-20)) {
// Setup auth.session.refresh request
var refreshRequest = {
"refreshToken": getRefreshToken(),
"clientID": getClientID(),
};
// Make auth.session.refresh request
$http.post(API + 'auth.session.refresh', format(refreshRequest))
.error(function (data) {
// If refresh request fails, logout and redirect to expired message
stopLoad(scope); logoff();
$window.location.href = '/error/expired';
return;
})
.success(function (data) {
// If refresh request succeeds, makeRequest is called recursively and the else condition runs
process(data, true);
return makeRequest(scope, address, request, basic, form);
});
} else { // if not logged in, or if session token is valid, run request function as usual
// Add Authorization header with valid sessionToken
if (ready()) $http.defaults.headers.post['Authorization'] = 'Bearer ' + getSessionToken();
// Basic Request: returns promise (if next context not set, can chain other action)
if (basic) {
return $http.post(API + address, request)
.error(function(data) {
if (data && scope) stopLoad(scope, data.message);
else if (scope) stopLoad(scope, Defaults.serverError);
else stopLoad();
if (form) resetForm(form);
})
.success(function(data) {
process(data);
if (scope) {
stopLoad(scope);
if (scope.context.next) $location.path(scope.context.next);
} else stopLoad();
if (form) resetForm(form);
});
}
// Custom Request: returns promise (can chain .error, .success)
else return $http.post(API + address, request);
}
};
當令牌被發現是無效的,但是,該函數返回undefined,我感到我不能運行.success()錯誤或.error()。其他功能運行,但我想知道如何確保我不會得到這個錯誤。謝謝!
你錯過在'return'聲明'if'體 – Bergi