Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative uri for node.js request library

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

const request = require('request')
const teamURL = `/users/${user._id}/teams`;

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

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

        res.render('userHome.html', {
            user: user,
            teams: body
        });
    } 
    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?

like image 275
Alexander Mills Avatar asked Mar 13 '15 06:03

Alexander Mills


People also ask

Can URI be relative?

Many systems, including most of the ones I have built and use day to day, have many internal relative links but really are better built without a knowledge of their own base URI, in that stored URIs are always relative.

What is Uri in node JS?

URI. js is a javascript library for working with URLs. It offers a "jQuery-style" API (Fluent Interface, Method Chaining) to read and write all regular components and a number of convenience methods like .

How do you access an array of objects in Node JS?

You need to look at the structure. An Object will start with an { and an Array will start with a [ . When you see an Object, you can use . propertyName to access propertyName .


2 Answers

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.

like image 65
Jasper Woudenberg Avatar answered Nov 06 '22 21:11

Jasper Woudenberg


Jasper 's answer is correct -- the request module needs full URL. if you are in a situation where you have a single page application, with lots of requests to an API with the same base URL, you can save a lot of typing by creating a module like this:

    var url = require('url'); 

    var requestParser = (function() {
      var href = document.location.href;
      var urlObj = url.parse(href, true);

      return { 
        href,
        urlObj,
        getQueryStringValue: (key) => {
          let value = ((urlObj && urlObj.query) && urlObj.query[key]) || null;
          return value;
        },
        uriMinusPath: urlObj.protocol + '//' + urlObj.hostname                                               
      };  
    })();

then, to grab the base URL anytime you need it: requestParser.uriMinusPath

and grab the value of an arbitrary query parameter: RequestParser.getQueryStringValue('partner_key');

like image 38
trad Avatar answered Nov 06 '22 21:11

trad