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

时间:2015-05-29 19:46:12

标签: node.js request logic superagent

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

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

2 个答案:

答案 0 :(得分:8)

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

如果您read through the src,您会看到use只在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
});

答案 1 :(得分:1)

最近发布了一个包superagent-use,以便于在全球范围内为超额请求设置使用。