如何在React Native IOS应用程序中发出HTTP请求?

Sar*_*mar 5 react-native react-native-ios

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);
       })
Run Code Online (Sandbox Code Playgroud)

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

小智 7

您可以尝试将此数据发送到服务器(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();
}
Run Code Online (Sandbox Code Playgroud)

编辑:最新的iOS sdk强制连接为https协议而不是http.you可以在Xcode项目的info.plist文件中为您的域添加例外.

如果你想允许一切写在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>
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看/sf/answers/2213637191/


归档时间:

查看次数:

6854 次

最近记录:

7 年,5 月 前