我一直在使用 Cordova 開發一個應用程式,該應用程式旨在在 iOS 和 Android 移動設備上運行。應用程式的一部分涉及向服務器發出 POST 請求,我最初是使用 XHR 請求實作的。它成功地發送資料并從服務器獲取答案,但是當在 iOS 物理設備或模擬器上運行相同的應用程式時,請求回傳 0 和空正文,就好像它沒有發送一樣。
我改用 fetch-api 試圖獲取更多資訊,現在我收到:
型別錯誤:加載失敗
我用那個特定的措辭找不到一個錯誤。
在 android 上,fetch-api 成功完成,服務器回應正確。
我的服務器確實有 SSL,我通過 HTTPS 發送請求。我還檢查了我不太熟悉的安全策略,但我正在使用以下內容(隱藏我的服務器的 url):
<meta http-equiv="Content-Security-Policy" content="default-src 'unsafe-inline' * 'self' server.url.com data: gap: https://ssl.gstatic.com 'unsafe-inline' 'unsafe-eval' ws: wss:; style-src 'self' 'unsafe-inline'; media-src *">
我還在 Info.plist 中添加了以下內容:
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>https://server.url.com/key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>
<dict>
最后,我還使用白名單插件添加了域。
發送帖子的javascript代碼如下:
let requestOptions = {
method: 'POST',
mode: cors,
credentials: 'same-origin',
cache: 'no-cache',
redirect: 'follow',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(out_data)
};
fetch(url, requestOptions)
.then(async response => {
const isJson = response.headers.get('content-type').includes('application/json');
const data = isJson && await response.json();
if (!response.ok) {
console.log(response.status);
const error = (data && data.message) || response.status;
alert("Request denied with error " response.status.toString())
return Promise.reject(error)
}
console.log(response.status);
console.log(JSON.stringify(data));
})
.catch(error => {
console.error("There was an error!", error);
alert(error);
});
uj5u.com熱心網友回復:
您可以改用cordova-plugin-ios-xhr并將首選項設定為
<preference name="AllowUntrustedCerts" value="true" />
<preference name="InterceptRemoteRequests" value="all" />
解決了XHR和iOS的很多問題
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/392449.html
標籤:javascript ios 科尔多瓦 xmlhttp请求 获取-api
下一篇:如何在React中選擇隨機組件
