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, ...)?
sounds like a bug with the superagent-prefix module. I would try there first.
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?
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?