# 发出网路请求

## 使用 `fetch` 发出网路请求 <a href="#vrr9c" id="vrr9c"></a>

`fetch` 函数是一个用于访问网络资源的工具，可以让您发送 HTTP 请求，并处理请求的响应。`fetch` 函数支持许多不同类型的请求，包括 `GET`、`POST`、`PUT` 和 `DELETE`，并支持请求体和响应体的自定格式。

使用 `fetch` 函数，可以方便地访问网络资源，并控制请求和响应的流程。例如，可以使用以下代码来发送一个 `GET` 请求，并在请求实现后处理响应：

```javascript
fetch('https://example.com/api/endpoint')
    .then(response => response.json())
    .then(data => {
    	// 在这里处理响应
    });
```

该示例代码会发送一个 GET 请求到指定的网络资源，然后在请求完成后，将响应体解析为 JSON 格式，并在这里处理解析后的响应体。

{% hint style="info" %}
若要了解 Javascript 中的 `fetch` 函数，建议可以阅读 MDN 网站上的介绍：\
<https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch>。

该文章介绍了 `fetch` 函数的基本用法，并提供了示例代码展示如何使用 `fetch` 来发送 HTTP 请求，并处理请求的响应。

此外，还可以参考下列文章了解更多关于 fetch 的信息：

* 《Using Fetch》（<https://davidwalsh.name/fetch>）
* 《Fetch API In Depth》（<https://css-tricks.com/using-fetch/>）
  {% endhint %}

***

## 使用 `https` 发出请求 <a href="#oowx7" id="oowx7"></a>

由于浏览器默认的安全性限制，`fetch` 方法有时候会遇到一些限制，这种情况下我们可以改采用 Node.js 原生的网络 API 来发送网络请求，获得更高的弹性。

使用 `https.get` 方法发送 HTTP GET 请求非常简单，只需要提供请求的 URL 即可。例如，可以使用以下代码来发送一个 HTTP GET 请求：

```javascript
const https = require('https');

https.get('https://www.example.com', (res) => {
  console.log(`Got response: ${res.statusCode}`);

  res.on('data', (d) => {
    // 处理响应数据
  });

}).on('error', (e) => {
  console.error(`Got error: ${e.message}`);
});
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://developer.eagle.cool/plugin-api/zh-cn/tutorial/network-request.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
