0

我必须在我的 Postman 预请求脚本中为 web api 调用创建一个身份验证哈希。我的集合将服务 URL 存储在一个名为 的集合级变量baseUrl中。这个变量的值为http://api-server.local

不幸的是,baseUrl当我尝试从pm.request.url. 我在我的预请求脚本{{baseUrl}}host属性中取回了一个值。pm.request.url

我的猜测是评估发生在请求创建管道的后期。

因此,我在我的集​​合中添加了一个新变量baseUrlHost,其值设置为api-server.local. 我打算使用这个新变量在我的身份验证哈希中正确设置主机。

与其做大量的字符串替换,我更愿意创建一个新Url对象。根据 Postman文档,可以使用 Url Node.js 模块。但是,当我创建一个Url对象时,它大部分都是空属性。

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);

这是输出...

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

我应该做些什么来正确初始化 Url 对象?

4

2 回答 2

0

好的,我为此挣扎了一会儿,发现使用 Postman IDE 提示有助于弄清楚如何包含 NodeJS“url”模块。

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"
}
于 2021-10-04T20:53:50.697 回答
0

在您的预请求脚本中尝试如下

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

console.log(urlObject);
于 2020-05-08T04:13:42.770 回答