【问题标题】:ReferenceError: fetch is not defined - PostmanReferenceError:未定义提取 - 邮递员
【发布时间】:2021-08-07 20:05:32
【问题描述】:

在 Postman 中,我运行一个任意请求。我将以下代码放入 Pre-req. 脚本或在 Tests 脚本中:

fetch('https://jsonplaceholder.typicode.com/todos/3')
  .then(response => response.text())
  .then(responseBody => {
    console.log('The response body:');
    console.log(responseBody);
  });

当我点击 Send 按钮运行请求时,我得到 ReferenceError: fetch 未定义

在线搜索时,我几乎没有找到有关此错误消息的任何信息 在邮递员。 现在,Postman 并不是一般意义上的网络浏览器,而是几乎所有 well known web browser offers the Fetch API 这些天。

Postman 没有实现 Fetch API 吗?

【问题讨论】:

    标签: javascript asynchronous fetch postman


    【解决方案1】:

    Postman 没有实现 Fetch API 吗?

    我认为不会。与fetch() 命令最接近的对应关系 是pm.sendRequest()
    但是pm.sendRequest returns a pm object and not a Promise, 至少现在。

    不过,我找到了一种解决方法。 在下面的代码 sn-p 中,我定义了 pmFetch() 函数,该函数旨在 执行fetch() 命令在普通网络浏览器中执行的操作。

    pmFetch('https://jsonplaceholder.typicode.com/todos/3')
      .then(response => response.json())
      .then(responseBody => {
        console.log('The response body:');
        console.log(responseBody);
        console.log('responseBody.title: "' + responseBody.title + '"');
      });
    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //
    function pmFetch (url) {
      return new Promise ((resolve, reject) => {
        pm.sendRequest(url, function (err, response) {
          if (err) reject(err);
          resolve(response);
        });
      });
    }
    

    这是link to the Postman Collection 如果您想下载、导入和运行该集合。

    参考:

    【讨论】:

      猜你喜欢
      • 2018-07-04
      • 1970-01-01
      • 2018-10-26
      • 2020-09-18
      • 2020-09-19
      • 2021-11-26
      • 2020-09-08
      • 2018-02-24
      • 1970-01-01
      相关资源
      最近更新 更多