Search code examples
node.jsnode-request

NodeJS request library how to get the full URL including URI and query string params


How does one extract/find the full URL from a HTTP request performed with the NodeJS request library. This would be useful for logging purposes.

Here's a code example to demonstrate:

request({
    baseUrl: 'https://foo.bar',
    url: '/foobar',
    qs: {
        page: 1,
        pagesize: 25
    }
}, (err, res, body) => {
    // Somewhere here I'd expect to find the full url from one of the parameters above
    // Expected output: https://foo.bar/foobar?page=1&pagesize=25
    console.log(res);
});

I can't seem to find any properties of the res param in the callback that contains the URL.

To clarify: by full URL I mean the URL constructed by the request library which should include the following fields:

  • Base URL (or just URI/URL when no base URL was set)
  • URL (or URI)
  • Query string parameters

Solution

  • Actually you can easily do that with store your request when you create it.

    const request = require('request');
    const myReq = request({
        baseUrl: 'https://foo.bar',
        url: '/foobar',
        qs: {
            page: 1,
            pagesize: 25
        }
    }, (err, res, body) => {
        console.log(myReq.host); // BASE URL
        console.log(myReq.href); // Request url with params
    });