![](/img/trans.png)
[英]typescript Cannot add headers to a fetch api using react-native
[英]React-Native Fetch API Works Differently Based On APIs
我們目前正在使用React-Native開發一個移動項目。 我們的應用程序依賴於API。 因此,我們使用React的fetch方法從API獲取數據。 我們的問題是,提取方法基於API的工作方式有所不同。 當我們使用API時,提取方法會引發網絡請求失敗錯誤。 我們嘗試了另一個公共API進行測試,它可以完美運行,沒有錯誤。
我在瀏覽器和Postman(測試API)上測試了所有API,它們都正確顯示了JSON響應。 但是,我們在提取方法上對其進行測試,其工作方式有所不同。 這是一些了解情況的代碼段:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
AlertIOS
} from 'react-native';
class Test extends Component {
constructor() {
super();
state = {
airports: []
}
}
onAfterLoad = (data) => {
AlertIOS.alert(
"Fetched Successfully"
);
this.setState({
airports: data.airports
});
}
componentWillMount() {
// Fails
let api1 = 'http://kolaybilet.webridge.co/api/v1/airports/ist/';
// Fails
let api2 = 'http://jsonplaceholder.typicode.com/posts/1/';
// Works
let api3 = 'https://randomuser.me/api/';
fetch(api1)
.then((r) => {
return r.json();
})
.then(this.onAfterLoad)
.catch((e) => {
AlertIOS.alert("An Error Has Occurred!", e.message);
});
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
</View>
);
}
}
問題圍繞iOS中的“應用程序傳輸安全性”策略。 randomuser API是SSL,而其他用戶則不是。
在您的XCode項目的info.plist
文件中,在NSAppTransportSecurity
詞典下添加鍵NSAllowsArbitraryLoads
,其值為YES
。 這將允許您成功提取其他端點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.