【发布时间】:2020-08-23 13:14:21
【问题描述】:
我必须在我的 Postman 预请求脚本中为 Web api 调用创建一个身份验证哈希。我的集合将服务 URL 存储在名为 baseUrl 的集合级变量中。这个变量的值为http://api-server.local
不幸的是,当我尝试从pm.request.url 直接使用baseUrl 变量时,它没有展开。我在预请求脚本的pm.request.url 的host 属性中取回了{{baseUrl}} 的值。
我的猜测是评估发生在请求创建管道的后期。
因此,我在集合中添加了一个名为baseUrlHost 的新变量,其值设置为api-server.local。我打算使用这个新变量在我的身份验证哈希中正确设置主机。
与其做大量的字符串替换,我更愿意创建一个新的Url 对象。根据 Postman documentation,可以使用 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 对象,我应该做些什么不同的事情?
【问题讨论】:
标签: postman postman-pre-request-script