【问题标题】:How can I use the URI module in a Postman Pre-Request Script?如何在 Postman 预请求脚本中使用 URI 模块?
【发布时间】:2020-08-23 13:14:21
【问题描述】:

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

不幸的是,当我尝试从pm.request.url 直接使用baseUrl 变量时,它没有展开。我在预请求脚本的pm.request.urlhost 属性中取回了{{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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      好的,我为此苦苦挣扎了一会儿,发现使用 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-05-11
        • 2020-02-29
        • 2017-11-23
        • 1970-01-01
        • 2022-01-16
        • 2018-11-15
        • 1970-01-01
        • 2017-01-25
        • 2018-02-28
        相关资源
        最近更新 更多