> For AI agents: the complete documentation index is available at /next/zh/llms.txt, the full documentation bundle is available at /next/zh/llms-full.txt.

# 网络

许多移动应用需要从远程 URL 加载资源。你可能想要向 REST API 发出 POST 请求，或者可能需要从另一台服务器获取大量静态内容。

## 使用 Fetch

:::tip

本功能依赖于已集成的 [Lynx Service](/next/zh/guide/start/integrate-with-existing-apps.md) 所提供的 HTTP 服务。

:::

Lynx 提供了与 Web 标准兼容的 [Fetch API](/next/zh/api/lynx-api/global/fetch.md)，用法与 Web 平台保持一致。你可以查阅 MDN 的[使用 Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) 指南了解更多信息。

以下示例展示了一个从 [JSONPlaceholder API](https://jsonplaceholder.typicode.com/) 获取并显示用户帖子的应用。该应用在启动后会显示加载状态，并在组件挂载（mounted）后触发 Fetch API 请求以获取帖子数据。获取的数据将显示在一个可滚动的列表中，其中每个帖子都包含其 `id` 和 `title`。如果请求仍在进行中，界面将显示 “Loading...” 消息。

**下面是一个示例: networking**

**Entry:** `src/fetch`
**Bundle:** `dist/fetch.lynx.bundle`

```tsx
import { root, useEffect, useState } from "@lynx-js/react";
import "./index.scss";

interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}

const App = () => {
  const [isFetching, setFetching] = useState(true);
  const [posts, setPosts] = useState<Post[]>([]);

  const getPosts = async () => {
    try {
      const json = await fetch(
        "https://jsonplaceholder.typicode.com/posts",
      ).then((res) => res.json());
      setPosts(json);
    } catch (error) {
      console.error(error);
    } finally {
      setFetching(false);
    }
  };

  useEffect(() => {
    getPosts();
  }, []);

  return (
    <scroll-view scroll-y className="scroll-view">
      {isFetching ? <text className="scroll-view__loading">Loading...</text> : (
        posts.map((post) => (
          <view id={`${post.id}`} className="scroll-view__post">
            <text>{`${post.id} : ${post.title}`}</text>
          </view>
        ))
      )}
    </scroll-view>
  );
};

root.render(<App />);

if (import.meta.webpackHot) {
  import.meta.webpackHot.accept();
}

```

v0.5.0



### 发起请求

要从任意 `URL` 获取内容，你可以将 `URL` 传递给 `fetch`：

```typescript
fetch('https://jsonplaceholder.typicode.com/todos/1');
```

`fetch` 还接受第二个可选参数，用于自定义 HTTP 请求。你可以指定额外的 `header`、发起 `POST` 请求或提供 `JSON` 格式的 `body`：

```typescript
fetch('https://jsonplaceholder.typicode.com/todos/1', {
  method: 'POST',
  headers: {
    'some-header': 'header',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  }),
});
```

请参阅 [Fetch Request](/next/zh/api/lynx-api/global/fetch.md#request) 了解 Lynx 支持的属性。

### 处理响应

以上示例展示了如何发起请求。在许多情况下，你还需要处理响应。

网络请求是一项异步操作。`fetch` 方法会返回一个 `Promise`，这使得编写异步代码变得非常简单。你可以使用 `async/await` 语法来等待 `Promise` 的解析：

```typescript
const getDataFromApiAsync = async () => {
  try {
    const response = await fetch(
      'https://jsonplaceholder.typicode.com/todos/1',
    );
    const json = await response.json();
    return json;
  } catch (error) {
    console.error(error);
  }
};
```

请参阅 [Fetch Response](/next/zh/api/lynx-api/global/fetch.md#response) 了解 Lynx 支持的属性。

不要忘记捕获 `fetch` 可能抛出的任何错误，否则它们将被静默忽略。

## 使用 Streaming Fetch

当需要传输大量数据时，服务端通常会采用 Streaming HTTP 的方式，将数据以流式形式逐步发送。此时，客户端可以利用 `fetch` 接口的流式处理能力，实时分批接收和处理数据，从而显著提升数据处理效率。

```typescript
fetch('https://sse.dev/test').then((response) => {
  const reader = response.body.getReader();
  while (true) {
    const { done, value } = await reader.read();
    if (done) {
      break;
    } else {
      const text = TextCodecHelper.decode(value);
      setData(text);
    }
  }
});
```

你可以查阅 MDN 文档的 [Response: body](https://developer.mozilla.org/en-US/docs/Web/API/Response/body)
了解如何处理 streaming body。

:::tip
试验性功能，页面中需要通过设置特定的 PageConfig `enableFetchAPIStandardStreaming = true`， 来开启 fetch 接口的流式读取能力。
:::

## 使用 EventSource

LynxSDK 提供 Web 标准完全一致的 `EventSource`，以处理 SSE 协议。

你可以查阅 MDN 文档的 [Using server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) 了解如何使用 `EventSource` 及 SEE 协议。

```typescript
const url = 'https://sse.dev/test';
const eventSource = new lynx.EventSource(url2);

eventSource.onmessage = (event) => {
  console.log('Received message:', event.data);
};

eventSource.onerror = (error) => {
  console.error('EventSource failed:', error);
};
```

## 使用 TextCodecHelper

由于 `PrimJS` 缺少对 `TextEncoder`/`TextDecoder` 的支持，Lynx 提供了 `TextCodecHelper` 以满足基本的编解码需求。该类支持在 `UTF-8` 编码下 `string` 与 `arraybuffer` 之间的转换。

用法如下：

将 `arraybuffer` 转换为 `string`：

```typescript
const str = TextCodecHelper.decode(arraybuffer);
```

将 `string` 转换为 `arraybuffer`：

```typescript
const arraybuffer = TextCodecHelper.encode(str);
```

## 使用其他网络库

Fetch API 已内置于 Lynx，这意味着你可以使用依赖于它的第三方库。

值得注意的是，Lynx 的 Fetch API 与 [Web Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) 相比存在细微差异。你可以查阅 [Fetch API 参考 - 兼容性](/next/zh/api/lynx-api/global/fetch.md#兼容性)部分以了解更多信息。因此，你可能需要调整来自 Web 生态系统的库以确保兼容性。如果你在使用 Lynx Fetch API 时遇到任何问题，欢迎提交功能请求或通过[贡献](https://github.com/lynx-family/lynx/blob/develop/CONTRIBUTING.md)来帮助 Lynx 更好地支持 Web 生态系统。

对于特定于前端框架的数据获取解决方案，例如在 ReactLynx 中使用 [TanStack Query (React Query)](https://tanstack.com/query/latest)，你可以参考 ReactLynx 指南的[数据获取](/next/zh/react/data-fetching.md)一章。
