简体   繁体   English

如果 node.js 出错,请重试请求

[英]Retry request if error with node.js

I have an application with node and my app is autenticated (as client) with JWT on an API.我有一个带有节点的应用程序,我的应用程序通过 API 上的 JWT 进行了身份验证(作为客户端)。

How can I refresh my token when I have an 401 error ?出现 401 错误时如何刷新令牌?

My project use not Express我的项目使用的不是 Express

my service :我的服务:

const request = require('request');

let config = require('../../configuration');

module.exports = {
    get_movies: function () {
        return new Promise((resolve, reject) => {
            request({
                method: 'GET',
                uri   : 'http://myapi/v1/movies',
                auth  : {
                    'bearer': config.token
                },
                json  : true
            }, function (error, response, body) {
                if (!error && response.statusCode === 200) {
                    resolve(body);
                } else {
                    reject(response);
                }
            })
        });
    },
    ...
    refreshToken: function () {
        return new Promise((resolve, reject) => {
            request({
                method: 'GET',
                uri   : 'http://myapi/v1/token-refresh',
                auth  : {
                    'bearer': config.token
                },
                json  : true
            }, function (error, response, body) {
                if (!error && response.statusCode === 200) {
                    resolve(body);
                } else {
                    reject(response);
                }
            })
        });
};

I would like to know if it's possible to intercept my (error 401) request on my get_movies function for example, call my refresh token function and after retry my previous function (get_movies) ?我想知道是否可以在我的 get_movies 函数上拦截我的(错误 401)请求,例如调用我的刷新令牌函数,然后重试我以前的函数(get_movies)?

A simple way would be to put an error handler after your get_movies promise to handle the case and retry.一种简单的方法是在get_movies承诺处理案例get_movies试之后放置一个错误处理程序。 Along the lines of:沿着以下路线:

get_retry: function () {
    return get_movies().catch((rejection) => {
        if (rejection.statusCode === 401)
            return refreshToken().then((x) => get_retry())
    })
}

Beware of the possibility of an infinite loop if your refreshToken() has a possibility to not fix the HTTP 401 .如果您的refreshToken()有可能无法修复HTTP 401请注意无限循环的可能性。

I have been using got for this and have been really happy with it.我一直为此使用got并且对它非常满意。

You can use the afterResponse hook to detect error, check that it is 401 and then refresh token and resubmit original request.您可以使用afterResponse钩子来检测错误,检查它是否为 401,然后刷新令牌并重新提交原始请求。

From the documentation:从文档:

const got = require('got');

const instance = got.extend({
    hooks: {
        afterResponse: [
            (response, retryWithMergedOptions) => {
                if (response.statusCode === 401) { // Unauthorized
                    const updatedOptions = {
                        headers: {
                            token: getNewToken() // Refresh the access token
                        }
                    };

                    // Save for further requests
                    instance.defaults.options = got.mergeOptions(instance.defaults.options, updatedOptions);

                    // Make a new retry
                    return retryWithMergedOptions(updatedOptions);
                }

                // No changes otherwise
                return response;
            }
        ],
        beforeRetry: [
            (options, error, retryCount) => {
                // This will be called on `retryWithMergedOptions(...)`
            }
        ]
    },
    mutableDefaults: true
});

It's working great for me so far :-)到目前为止,它对我来说很好用 :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM