【问题标题】:Retry REST call using error interceptor with Restangular使用带有 Restangular 的错误拦截器重试 REST 调用
【发布时间】:2015-03-15 12:32:11
【问题描述】:

我想在 Restangular 1.4.0 出现某些情况后重试呼叫。所以我在文档中设置了一个setErrorInterceptor。它有效,但第一次调用的then 子句未执行。 responseHandler 在错误拦截器中返回 undefined

我的客户代码:

Restangular.setErrorInterceptor(function (response, deferred, responseHandler) {
    console.log('error interceptor');
    console.log(response.status);
    if (response.status === 403) {
        //refreshAccesstoken().then(function() {
        //  // Repeat the request and then call the handlers the usual way.
        //  $http(response.config).then(responseHandler, deferred.reject);
        //  // Be aware that no request interceptors are called this way.
        //});

        return false; // error handled
    } else if (response.status === 401) {
        return $http.get('http://192.168.0.27:3000/auth/guest').then(function (result) {
            var token = result.data.token;
            Auth.setToken(token);
            response.config.headers.Authorization = 'Bearer ' + Auth.getToken();
            console.log(responseHandler);
            //response.config.headers["Authorization"] =  Auth.getToken();
            $http(response.config).then(responseHandler, deferred.reject);
            //return token;
            return false;
        });
        //$http(response.config).then(responseHandler, deferred.reject);

    }
    console.log('error not handled');
    return true; // error not handled
});

Dashboards.post()
    .then(function (result) {
        console.log(result);
        return Restangular.oneUrl('newDash', result.data).get();
    }, function (response) {
        console.log("Error with status code", response.status);
    })
    .then(function (result) {
        console.log(result);
    });

我的服务器日志:

POST /api/v1/dashboards HTTP/1.1" 401
GET /auth/guest HTTP/1.1" 200
POST /api/v1/dashboards HTTP/1.1" 201

【问题讨论】:

    标签: angularjs restangular


    【解决方案1】:

    我使用 deferred.resolve 作为第一个参数,而不是 responseHandler$http(response.config).then(deferred.resolve, deferred.reject);

    【讨论】:

      【解决方案2】:

      如果您从不同的域/主机访问 REST API,那么您遇到了 CORS 问题。

      JavaScript(包括 AngularJS)不允许在自己的域之外发出请求,除非服务器明确允许,并且您的脚本专门要求访问。

      这个 StackOverflow 问题实际上回答了我的问题,它现在连接到我的 REST 服务:

      Restangular crossdomain request. What I do wrong?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-29
        • 2015-04-16
        • 1970-01-01
        • 1970-01-01
        • 2015-11-13
        • 1970-01-01
        相关资源
        最近更新 更多