Method ".use" to add logic for each SuperAgent request

This issue in the SuperAgent repository mentions the .use method to add logic for each request. For example, adding an Authorization header for the JWT when a token is available:

 superagent.use( bearer ); function bearer ( request ) { var token = sessionStorage.get( 'token' ); if ( token ) request.set( 'Authorization', 'Bearer ' + token ); } 

Although the last comment says that this function works again, I cannot get it to work.

The following test code:

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

It returns this error:

 request.use( bearer ); ^ TypeError: undefined is not a function 
+7
logic request use superagent
source share
2 answers

The problem you are connected with is not related to any commit, so we can only assume whether this function was implemented and then deleted or not implemented in the first place.

If you read src , you will see that use is defined only in the prototype of the Request constructor, that is, it can only ever after you start creating a request as shown in the readme file .

In other words, the problem seems to be related to a function that was deleted or never existed. Instead, you should use the syntax specified in 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 ); } } 

Of course, you can create your own wrapper so you don't have to do this for every request.

 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 }); 
+8
source share

The superagent-use package has recently been released to make it easy to configure global usage for superagent requests.

+1
source share

All Articles