view raw
Alex Mills Alex Mills - 11 months ago 102
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 {

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


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 and find a link /questions, it's clear from context the full url should be

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('', '/users/15/teams');
console.log(fullUrl); //=> '');

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