# 發出網路請求

## 使用 `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-tw/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.
