如何在 React Native IOS 应用程序中发出 HTTP 请求? [英] How to Make HTTP Requests In React Native IOS application?

查看:33
本文介绍了如何在 React Native IOS 应用程序中发出 HTTP 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

fetch('http://119.9.52.47:3000/api/countries', {
       method: 'POST',
       headers: { 'Accept': 'application/json','Content-Type': 'application/json'},
   }).then((response) => response.json())
     .then((responseData) => {
           console.log(responseData);
       })

这是我的代码.但这行不通.

Here is my code . But that's not work.

推荐答案

你可以试试这样发送数据到服务器(POST)

you can try like this for send data to server(POST)

let response = await fetch(
    'http://your_url', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        username: this.state.name,//data which u want to send
        password: this.state.password,
      })
  });
  let responseText = await response.text();
  if (response.status >= 200 && response.status < 300){
    Alert.alert('Server response', responseText)

  }
  else {
    let error = responseText;
    throw error
    //Alert.alert('Login', error)
  }
} catch(errors) {
  Alert.alert('Login', errors)

  Actions.Documents();
}

由于最新的 iOS sdk 强制连接使用 https 协议而不是 http.您可以在 Xcode 项目的 info.plist 文件中向您的域添加例外.

As latest iOS sdk enforces connection to be in https protocol instead of http.you can add an exception to your domain inside info.plist file of the Xcode project.

如果你想让一切都写在 info.plist 中

if you want to allow everything write this inside info.plist

<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
    <key>yourdomain.com</key>
    <dict>
        <!--Include to allow subdomains-->
        <key>NSIncludesSubdomains</key>
        <true/>
        <!--Include to allow HTTP requests-->
        <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
        <true/>
        <!--Include to specify minimum TLS version-->
        <key>NSTemporaryExceptionMinimumTLSVersion</key>
        <string>TLSv1.1</string>
    </dict>
 </dict>
</dict>

有关详细信息,请查看https://stackoverflow.com/a/31623388/7604342

这篇关于如何在 React Native IOS 应用程序中发出 HTTP 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆