2017-03-08 99 views
1
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); 
     }) 

这是我的代码。但那不行。如何在React Native IOS应用程序中创建HTTP请求?

+0

现在编辑我的答案检查它 –

+0

在哪个info.plist文件中我必须添加App Transport安全例外? 因为应用程序文件夹中有更多info.plist文件。 –

+0

搜索AppName-Info.plist,其中AppName是您的应用的名称。 –

回答

2

你可以尝试这样的数据发送到服务器(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.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> 

更多信息检查了这一点https://stackoverflow.com/a/31623388/7604342

+0

在“let responseText = await response.text();”中出现了一个问题;“@Nitesh Mishra –

+0

错误:语法错误”await“是保留字。 –

+0

现在编辑我的代码尝试它不会显示错误 –

0

报价Network docs

默认,iOS将阻止任何请求未使用SSL进行加密。如果您需要从明文网址(以http开头)获取数据,则首先需要添加App Transport Security异常。

您的请求是http,因此您需要将地址作为App Transport Security异常添加到您的ios应用中,或者使用https。

+1

如何将地址添加到App Transport Security异常? 请您简单介绍一下吗? @Moti Azu –

+0

我有同样的问题。你找到解决方案吗? –

相关问题