Superagent: Adding a prefix to all requests

Created on 8 Jan 2015  路  4Comments  路  Source: visionmedia/superagent

I'm searching for a way to add a prefix to all requests. I tried using the superagent-prefix, but it didn't work as documented. If I execute the code as listed on the frontpage, I get an error. For example:

var request = require('superagent');
var prefix = require('superagent-prefix')('http://127.0.0.1');

prefix(request);

request.get('/api/entity').end([...]);

Leads to

TypeError: Cannot read property '0' of undefined
[...] 

It turned out, that superagent-prefix can only be applied to a single(!) request:

var request = require('superagent');
var prefix = require('superagent-prefix')('http://127.0.0.1');

prefix(request.get('/api/entity')).end([...]);

Is there a way to configure superagent to apply a prefix for all requests without monkey patching every REST-method (get, post, ...)?

Most helpful comment

Even if there's a plugin that addresses this issue, isn't this a common use case and a good feature to have in the core library?

All 4 comments

sounds like a bug with the superagent-prefix module. I would try there first.

  1. superagent-prefix never claimed to offer this functionality. Only the superagent documentation is stating this: "Prefixes _all_ requests"
  2. superagent-prefix doesn't seem to be maintained anymore
  3. I don't think that this is a superagent-prefix bug. It consists of only 9 lines of code and seems to do exactly, what it is supposed to do: Add a prefix to a _single_ request:
module.exports = function (prefix) {
    return function (request) {
        if (request.url[0] === '/') {
            request.url = prefix + request.url;
        }

        return request;
    };
}

This is why I am asking, how this could be achieved just by using vanilla superagent.

@tbo recently I use superagent to do the same thing.

Fortunely, I find https://www.npmjs.com/package/superagent-defaults to solve my problem.

var superagent = require('superagent-defaults')();
superagent.on('request', function (request) {
  if (request.url[0] === '/') {
    request.url = 'http://127.0.0.1:3001' + request.url;
  }
});

Good luck

Even if there's a plugin that addresses this issue, isn't this a common use case and a good feature to have in the core library?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tj picture tj  路  4Comments

noway picture noway  路  4Comments

tj picture tj  路  9Comments

ariemeow picture ariemeow  路  8Comments

djizco picture djizco  路  5Comments