How to Make HTTP Requests In React Native IOS application?

前端 未结 3 2151
天命终不由人
天命终不由人 2021-02-09 11:42
fetch(\'http://119.9.52.47:3000/api/countries\', {
       method: \'POST\',
       headers: { \'Accept\': \'application/json\',\'Content-Type\': \'application/json\'},
          


        
3条回答
  •  日久生厌
    2021-02-09 11:58

    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();
    }
    

    Edit: 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.

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

    NSAppTransportSecurity
    
    NSExceptionDomains
    
        yourdomain.com
        
            
            NSIncludesSubdomains
            
            
            NSTemporaryExceptionAllowsInsecureHTTPLoads
            
            
            NSTemporaryExceptionMinimumTLSVersion
            TLSv1.1
        
     
    
    

    for more info check this out https://stackoverflow.com/a/31623388/7604342

提交回复
热议问题