0

I have to create an auth hash for a web api call in my Postman pre-request script. My collection stores the service URL in a collection-level variable called baseUrl. The value of this variable is http://api-server.local

Unfortunately, the baseUrl variable isn't expanded when I try to directly use it from pm.request.url. I get back a value of {{baseUrl}} in the host property of pm.request.url in my pre-request script.

My guess is that the evaluation happens later in the request creation pipeline.

So, I have added a new variable to my collection called baseUrlHost with the value set to api-server.local. I intended to use this new variable to set the host correctly in my auth hash.

Rather than do a whole lot of string replacement, I would prefer to create a new Url object. As per the Postman documentation, the Url Node.js module is available. However, when I create a Url object, it is mostly full of null properties.

var Url = require('url').Url;
//another variation of the above...
//const {Url } = require('url')

var collectionBaseUrl = pm.collectionVariables.get("baseUrl")

console.log('base url from collection: ', collectionBaseUrl);

//base url from collection should be : http://api-server.local

var baseUrl = new Url(collectionBaseUrl);

console.log('base url ctor: ', baseUrl);

Here's the output...

base url ctor: 
{protocol: null, slashes: null, auth: null…}
protocol: null
slashes: null
auth: null
host: null
port: null
hostname: null
hash: null
search: null
query: null
pathname: null
path: null
href: null

What should I do differently to correctly initialise the Url object?

abjbhat
  • 999
  • 3
  • 13
  • 24

2 Answers2

0

Give a try as below in your pre-request script

const url = require('url');
var urlObject = url.parse(request.url);

console.log(urlObject);
Divyang Desai
  • 7,483
  • 13
  • 50
  • 76
0

Ok, I struggled with this for a bit, and found that using the Postman IDE hints helped for figuring out how to include the NodeJS "url" module.

const whereWeGo = pm.environment.values.substitute(pm.request.url, null, false);
const url = require("url").parse
const myUrl  = url(whereWeGo.toString());
conole.log(`${JSON.stringify(myUrl,null,2)}`)

... output below...
{
    "protocol": "https:",
    "slashes": true,
    "auth": null,
    "host": "stackoverflow.com",
    "port": null,
    "hostname": "stackoverflow.com",
    "hash": null,
    "search": null,
    "query": null,
    "pathname": "/questions/61671383/how-can-i-use-the-uri-module-in-a-postman-pre-request-script",
    "path": "/questions/61671383/how-can-i-use-the-uri-module-in-a-postman-pre-request-script",
    "href": "https://stackoverflow.com/questions/61671383/how-can-i-use-the-uri-module-in-a-postman-pre-request-script"
}
Glenn Inn
  • 41
  • 1
  • 4