# HTTP 客户端支持的 JavaScript API

> For the complete documentation index, see [llms.txt](https://www.jetbrains.com.cn/help/idea/llms.txt).

## console.log

HTTP 客户端 支持  `console.log()`  方法，将文本值（或用顿号分隔的多个值）打印到响应处理程序或预请求处理程序脚本的输出中。 您也可以使用 [client.log](http-client-reference.html) 达到相同的目的。 示例：

```HTTP_REQUEST_FULL
GET example.org

> {%
    console.log(response.status)
%}

```

您还可以传递一个 JavaScript 对象（例如，  `console.log(response.body)` ），它将在输出中以 JSON 格式显示，并带有适当的语法高亮显示。

## DOM 方法和属性

HTTP 客户端支持一些 DOM 树的方法和属性，使您能够解析和操作作为响应体一部分接收的 XML 和 HTML 文档（或使用 [DOMParser](#DOMParser) 创建的文档）。 支持的方法包括：

[getElementsByTagName()](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName)
: 返回具有指定标签名称的元素集合。 例如：
:
:
:
:
: ```HTTP_REQUEST_FULL
: GET https://examples.http-client.intellij.net/xml
:
: > {%
: const slide = response.body.getElementsByTagName("slide")[0]
: console.log(slide)
: %}
:
: ```

[getElementsByName()](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName)
: 返回具有给定  `名称`  属性的节点集合。 例如：

[getElementById()](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)
: 通过其  `id` 检索 Element 对象。

[getElementsByClassName()](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName)
: 返回具有指定类名的所有子元素的类数组对象。

[DOMParser](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser)
: 将 XML 或 HTML 源代码从字符串解析为 DOM 文档，使用  `parseFromString()` 方法。 例如：
:
:
:
:
: ```HTTP_REQUEST_FULL
:
: GET example.org
:
: > {%
: const xmlStr = '<q id="a"><span class="test" id="b">hey!</span><span id="bar">world</span><foo class="test" id="x-foo"/><bar name="x-foo"/></q>';
: const doc = new DOMParser().parseFromString(xmlStr, "application/xml");
:
: console.log(doc.getElementById("a"))
: console.log(doc.getElementById("b"))
: console.log(doc.getElementsByClassName("test"))
: console.log(doc.getElementsByTagName("span"))
: console.log(doc.getElementsByName("x-foo"))
: %}
:
:
: ```

[createElement(tagName)](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement)
: 创建指定的 HTML 元素  `tagName` 。
:
:
:
:
: ```HTTP_REQUEST_FULL
:
: GET example.org
:
: > {%
: const xmlStr = '<q id="a"><span class="test" id="b">hey!</span><span id="bar">world</span><foo class="test" id="x-foo"/><bar name="x-foo"/></q>';
: const doc = new DOMParser().parseFromString(xmlStr, "application/xml");
: const bodyElement = doc.createElement("body");
: %}
:
:
: ```

开始输入方法名称，以获取受支持方法的补全。 将鼠标悬停在上面以获取快速文档。 要查看所有支持的 DOM 方法和属性，请展开以下部分：

### 支持的方法

|   `Node`  方法  |   `文档`  方法  |
| --- | --- |
|      * `[cloneNode()](https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode)`    * `[compareDocumentPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition)`    * `[contains()](https://developer.mozilla.org/en-US/docs/Web/API/Node/contains)`    * `[getRootNode()](https://developer.mozilla.org/en-US/docs/Web/API/Node/getRootNode)`    * `[hasChildNodes()](https://developer.mozilla.org/en-US/docs/Web/API/Node/hasChildNodes)`    * `[insertBefore()](https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore)`    * `[isConnected()](https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected)`    * `[isDefaultNameSpace()](https://developer.mozilla.org/en-US/docs/Web/API/Node/isDefaultNamespace)`    * `[isEqualNode()](https://developer.mozilla.org/en-US/docs/Web/API/Node/isEqualNode)`    * `[isSameNode()](https://developer.mozilla.org/en-US/docs/Web/API/Node/isSameNode)`    * `[lookupNamespaceURI()](https://developer.mozilla.org/en-US/docs/Web/API/Node/lookupNamespaceURI)`    * `[lookupPrefix()](https://developer.mozilla.org/en-US/docs/Web/API/Node/lookupPrefix)`    * `[nextSibling()](https://developer.mozilla.org/en-US/docs/Web/API/Node/nextSibling)`    * `[normalize()](https://developer.mozilla.org/en-US/docs/Web/API/Node/normalize)`    * `[removeChild()](https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild)`    * `[replaceChild()](https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild)`    |      * `[createElement(tagName)](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement)`    * `[getElementById()](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)`    * `[getElementsByClassName()](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName)`    * `[getElementsByName()](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName)`    * `[getElementsByTagName()](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName)`    |

### 支持的属性

|   `Element`  属性  |   `Node`  属性  |
| --- | --- |
|      * `[className](https://developer.mozilla.org/en-US/docs/Web/API/Element/className)`    * `[id](https://developer.mozilla.org/en-US/docs/Web/API/Element/id)`    * `[标签名称](https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName)`    |      * `[isConnected](https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected)`    * `[firstChild](https://developer.mozilla.org/en-US/docs/Web/API/Node/firstChild)`    * `[lastChild](https://developer.mozilla.org/en-US/docs/Web/API/Node/lastChild)`    * `[nextSibling](https://developer.mozilla.org/en-US/docs/Web/API/Node/nextSibling)`    * `[nodeName](https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeName)`    * `[nodeType](https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType)`    * `[nodeValue](https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeValue)`    * `[ownerDocument](https://developer.mozilla.org/en-US/docs/Web/API/Node/ownerDocument)`    * `[parentNode](https://developer.mozilla.org/en-US/docs/Web/API/Node/parentNode)`    * `[previousSibling](https://developer.mozilla.org/en-US/docs/Web/API/Node/previousSibling)`    * `[文本内容](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent)`    |

## URLSearchParams

`URLSearchParams`  是一个 JavaScript 对象，使处理 URL 查询字符串部分变得容易。  `URLSearchParams`  接受以下格式的参数：

* 查询字符串： `URLSearchParams("key=value&key2=value2");`

* 表示 URL 参数的键值对： `URLSearchParams({ key1: "value1", key2: "value2" })`

* 键-值对数组： `URLSearchParams([["key1", "value1"], ["key2", "value2"]])`

HTTP 客户端支持 [all known URLSearchParams methods](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams#instance_methods)。 示例：

```HTTP_REQUEST_FULL
< {%

      client.global.set('query', 'foo=1&bar=2')

      const params = new URLSearchParams(client.global.get('query'));
      const params2 = new URLSearchParams([["planet", "tatooine"], ["year", "2"]]);
      const params3 = new URLSearchParams({key1: "value1", key2: "value2"});

      console.log(params.has("bar")); // outputs true
      console.log(params.has("param")); // outputs false
      params.append("foo", 3);
      console.log(params.getAll("foo")); // outputs ["1","3"]

      for (let value of params.values()) {
          console.log(value);  // outputs 1 2 3
      }

      for (let key of params2.keys()) {
          console.log(key);  // outputs planet year
      }

      client.global.set("query",params.toString())
   %}

  GET example.org/{{query}}

```

## Base64 编码：btoa 和 atob

HTTP 客户端支持 [btoa()](https://developer.mozilla.org/en-US/docs/Web/API/Window/btoa) 和 [atob()](https://developer.mozilla.org/en-US/docs/Web/API/Window/atob) 方法。

* 使用 `Window.btoa(stringToEncode)` 或 `btoa(stringToEncode)` 从 `stringToEncode` 字符串创建 Base64 编码的 ASCII 字符串。

* 使用 `Window.atob(encodedData)` 或 `atob(encodedData)` 解码使用 Base64 编码的数据字符串。

例如：

```HTTP_REQUEST_FULL
GET https://examples.http-client.intellij.net/ip

> {%
    const encodedData = Window.btoa("Hello, world"); // encode a string
    const decodedData = Window.atob(encodedData); // decode the string
    console.log(decodedData); // prints "Hello, world"
%}

```

## 执行 shell 命令

为了让您通过运行 shell 命令与操作系统交互，HTTP 客户端支持以下方法：

[exec(command\[, options\]\[, callback\])](https://nodejs.org/api/child_process.html#child_processexeccommand-options-callback)
: 启动一个 shell，然后在该 shell 中执行命令，并缓冲任何生成的输出。

[execFile(file\[, args\]\[, options\]\[, callback\])](https://nodejs.org/api/child_process.html#child_processexecfilefile-args-options-callback)
: 与  `exec()`  类似，但默认情况下不会启动 shell。

[execSync(command\[, options\])](https://nodejs.org/api/child_process.html#child_processexecsynccommand-options)
: 与  `exec()`  相同，但该方法在子进程完全关闭之前不会返回。

[execFileSync(file\[, args\]\[, options\])](https://nodejs.org/api/child_process.html#child_processexecfilesyncfile-args-options)
: 与  `execFile()`  相同，但该方法在子进程完全关闭之前不会返回。

[spawn(command\[, args\]\[, options\])](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options)
: 启动一个 shell，然后在该 shell 中执行命令，并缓冲任何生成的输出。

[spawnSync(command\[, args\]\[, options\])](https://nodejs.org/api/child_process.html#child_processspawnsynccommand-args-options)
: 与  `spawn()`  相同，但该函数在子进程完全关闭之前不会返回。

支持的选项包括：

cwd
: 指定应在其中执行命令的目录。

env
: 指定应为进程提供的一组环境变量。

timeout
: 进程允许运行的最长时间（以毫秒为单位）。

maxBuffer
: 为输出的大小设置一个最大限制（以字符为单位）。

命令解释器
: 指定用于执行命令的 shell。

信号
: 指定在需要终止进程时发送的信号。

回调
: 不是一个选项，而是一个单独的参数，可以传递给异步方法。 回调是一个函数，当进程终止时将调用该函数。

例如：

```HTTP_REQUEST_FULL

### List all directories in the specified folder

GET https://examples.http-client.intellij.net

> {%
  const result = execSync("ls -l", {
      cwd: '/Users/John.Doe/Docs/'
  })
  console.log(`result: ${result}`)
%}


### Pass an environment variable to the process

< {%
  const result = execSync('bash -c "set"', {
    env : {
      name: 'John'
    }})
  console.log(`result: ${result}`)
 %}

GET https://examples.http-client.intellij.net

```

