“.use”方法在 SuperAgent 的每个请求上添加逻辑

".use" method to add logic on each request of SuperAgent

SuperAgent 存储库中的 issue 提到了 .use 方法来为每个请求添加逻辑。例如,当令牌可用时,为 JWT 添加 Authorization header:

superagent.use( bearer );

function bearer ( request ) {
    var token = sessionStorage.get( 'token' );

    if ( token ) request.set( 'Authorization', 'Bearer ' + token );
}

虽然最后一条评论说这个功能又能用了,但我还是没能用。

以下测试代码:

var request = require( 'superagent' );

request.use( bearer );

function bearer ( request )
{
    // "config" is a global var where token and other stuff resides
    if ( config.token ) request.set( 'Authorization', 'Bearer ' + config.token );
}

Returns 这个错误:

request.use( bearer );
        ^
TypeError: undefined is not a function

您链接到的问题与任何提交都没有关联,因此我们所能做的就是推测该功能是否已实现然后删除,或者一开始就从未实现。

如果你read through the src, you will see that use is only ever defined on the prototype of the Request constructor, meaning it can only ever be used after you've began constructing a request, as shown in the readme.

换句话说,这个问题似乎是在谈论一项已被删除或从未存在过的功能。您应该改用自述文件中提到的语法。

var request = require('superagent');

request
.get('/some-url')
.use(bearer) // affects **only** this request
.end(function(err, res){
    // Do something
});

function bearer ( request ){
    // "config" is a global var where token and other stuff resides
    if ( config.token ) {
        request.set( 'Authorization', 'Bearer ' + config.token );
    }
}

您当然可以创建自己的包装器,这样您就不必为每个请求都这样做。

var superagent = require('superagent');

function request(method, url) {
    // callback
    if ('function' == typeof url) {
        return new superagent.Request('GET', method).end(url).use(bearer);
    }

    // url first
    if (1 == arguments.length) {
        return new superagent.Request('GET', method).use(bearer);
    }

    return new superagent.Request(method, url).use(bearer);
} 
// re-implement the .get and .post helpers if you feel they're important..

function bearer ( request ){
    // "config" is a global var where token and other stuff resides
    if ( config.token ) {
        request.set( 'Authorization', 'Bearer ' + config.token );
    }
}

request('GET', '/some-url')
.end(function(err, res){
    // Do something
});

最近发布了包 superagent-use 以方便为超级代理请求设置全局使用。