7

SuperAgent 存储库中的这个问题提到了.use在每个请求上添加逻辑的方法。例如,Authorization在令牌可用时为 JWT 添加标头:

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 );
}

返回此错误:

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

2 回答 2

9

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

如果您通读 src,您会看到use它只在构造函数的原型上定义Request,这意味着它只能在您开始构建请求后才能使用,如自述文件中所示

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

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
});
于 2015-05-29T20:10:09.613 回答
1

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

于 2016-02-28T13:59:35.150 回答