网络和安全

Fetch

详细介绍可查看 MDN 的文档:Using Fetcharrow-up-right

在 React Native 中可使用 Fetch APIarrow-up-right 发送网络请求。

Making requests

示例:

fetch('https://mywebsite.com/mydata.json');

Fetch 也提供了一个可选的参数来设置 HTTP Method 、 Header 、 Body 等。完整的参数列表可参考 Fetch Request docsarrow-up-right

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue'
  })
});

Handling the response

网络本质上是一种异步操作。Fetch 方法将返回一个 Promisearrow-up-right ,它使异步代码的编写变得简单:

你也可以在 React Native 中使用 async / await 语法:

可运行的示例

Using Other Networking Libraries

XMLHttpRequest APIarrow-up-right 是内建在 React Native 里的。这意味着您可以使用依赖于它的第三方库,如 axiosarrow-up-right ,或者直接使用 XMLHttpRequest

The security model for XMLHttpRequest is different than on web as there is no concept of CORSarrow-up-right in native apps.

WebSocket Support

React Native 也支持 WebSocketsarrow-up-right (一种在单个 TCP 连接上提供全双工通信通道的协议)。

Security

https://reactnative.dev/docs/securityarrow-up-right

Last updated