Fetch 在 React Native 中不起作用 ios
Fetch doesn't work in React Native ios
我在尝试获取数据的 React Native 中有登录功能。函数如下:
onLogin: function() { //
const self = this;
self.setState({modalVisible: true, modalMessage: 'Signing in'});
fetch('http://psa.autralis.com/manager/api/v1/obtain-auth-token/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: self.state.username,
password: self.state.password,
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch((error) => {
console.warn(error);
});
},
但由于某些原因,它不适用于 ios。我收到一个错误:
在 android 上有效,我用 postman 测试过它也有效。
有什么想法吗?
出现这个问题的原因是:iOS默认不允许http请求,只允许https。如果您需要使用 http 执行此操作,只需更改您的 info.plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
以防其他人需要它。我通过添加
解决了它
<key>NSAllowsArbitraryLoads</key>
<true/>
到位于项目 ios
文件夹内的 Info.plist
文件。
于是我改变了
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
和
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
我在尝试获取数据的 React Native 中有登录功能。函数如下:
onLogin: function() { //
const self = this;
self.setState({modalVisible: true, modalMessage: 'Signing in'});
fetch('http://psa.autralis.com/manager/api/v1/obtain-auth-token/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: self.state.username,
password: self.state.password,
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch((error) => {
console.warn(error);
});
},
但由于某些原因,它不适用于 ios。我收到一个错误:
在 android 上有效,我用 postman 测试过它也有效。
有什么想法吗?
出现这个问题的原因是:iOS默认不允许http请求,只允许https。如果您需要使用 http 执行此操作,只需更改您的 info.plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
以防其他人需要它。我通过添加
解决了它<key>NSAllowsArbitraryLoads</key>
<true/>
到位于项目 ios
文件夹内的 Info.plist
文件。
于是我改变了
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
和
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>