2017-03-08 131 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

我有同樣的問題。你找到解決方案嗎? –

相關問題