在发出 HTTP 请求之前,我需要检查我拥有的访问凭据是否有效。如果它们无效,我需要发出第一个 HTTP 请求来重新验证它们,并在完成后发出第二个 HTTP 请求(原始请求)。该函数调用需要从第二个 HTTP 请求返回 Angular 的 $http
Promise。这是我的功能:
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);
}
};
但是,当发现 token 无效时,该函数返回未定义,并且出现无法运行 .success() 或 .error() 的错误。 else 功能运行,但我想知道如何确保不会收到此错误。谢谢!
最佳答案
只需返回上面的 $http.post(/*...*/)
并让 Promise 链发挥它的魔力:
return $http.post(API + 'auth.session.refresh', format(refreshRequest))
.catch(function (response) {
// If refresh request fails, logout and redirect to expired message
stopLoad(scope); logoff();
$window.location.href = '/error/expired';
})
.then(function (response) {
// If refresh request succeeds, makeRequest is called recursively and the else condition runs
process(response.data, true);
return makeRequest(scope, address, request, basic, form);
});
更新:由于 .success
/.error
函数不可链接(并且已被标记为 deprecated ),您应该使用 .then
和 .catch
代替。
$http.post(/*...*/)
.success(function(data) {
/* do something with data */
})
.error(function(err) {
/*...*/
});
变成
$http.post(/*...*/)
.then(function(response) {
/*do something with response.data */
})
.catch(function(response) {
/*...*/
});
关于javascript - 链 2 个 HTTP 请求并返回第二个 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37911413/