Alex Mills Alex Mills - 5 months ago 55
Node.js Question

Relative uri for node.js request library

I have the following code, and node.js can't resolve the url:

var teamURL = '/users/' + user._id + '/teams';

var req = request({
url: teamURL,
json: true
}, function(error, response, body) {

if (!error && response.statusCode == '200') {

//var teams = JSON.stringify(body);
var teams = body;

res.render('userHome.html', {
user: user,
teams: teams
});
} else {
console.error(error);
next(error);
}
});


is there a good way to use relative paths/urls with the request library on a server-side node.js Express app?

Answer

Giving just a relative url only works if it is clear from context what the root part of the url should be. For instance, if you are on stackoverflow.com and find a link /questions, it's clear from context the full url should be stackoverflow.com/questions.

The request library doesn't have this kind of context information available, so it needs the full url from you to do be able to make the request. You can build the full url yourself of course, for instance by using url.resolve():

var url = require('url');
var fullUrl = url.resolve('http://somesite.com', '/users/15/teams');
console.log(fullUrl); //=> 'http://somesite.com/users/15/teams');

But of course this will still require you to know the root part of the url.

Comments