我的测试 CURL(获取)调用有效。
问题: 我的 Ionic React 应用程序 iOS 中的相同 URL(用于 CURL)(使用
Axios
或 fetch()
)给我一个错误。
--- 这是有效的 CURL
curl -X 'GET' \
'https://www.website.com/filehandlingverifiedsession?seskey=0000000005711040000202405141237080003968400278187&id=94520' \
-H 'accept: */*' \
-H 'Content-Type: text/plain'
--- 这是我在终端中得到的有效结果,一切正常
--- 现在在我的 Ionic React 应用程序中,我使用 Axios 调用确切的 URL,但这会产生错误。
const handleDownload = (documentID: string) => {
console.log('ƒ handleDownload mxapp axios', documentID);
var url = 'https://www.website.com/filehandlingverifiedsession'; //?seskey='+store.userSessionKey+'&id='+documentID;
console.log('url', url);
axios.get(url, {
params: {
seskey: store.userSessionKey,
id: documentID,
}
})
.then(function (response) {
console.log('success');
console.log(response);
})
.catch(function (error) { // from https://github.com/axios/axios?tab=readme-ov-file#handling-errors
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
})
.finally(function () {
console.log('always');
// always executed
});
return;
}
作为有相同问题的任何人的参考/跟进...
仅当使用 Safari 并将开发工具连接到 xCode 中的 iPhone 模拟器时,问题才会变得明显。
下面解决了它。此处的文档:https://ionicframework.com/docs/troubleshooting/cors
response.addHeader("Access-Control-Allow-Origin", "capacitor://localhost"); // iOS
response.addHeader("Access-Control-Allow-Origin", "http://localhost"); // Android
response.addHeader("Access-Control-Allow-Methods", "POST, GET"); // , PUT, UPDATE, OPTIONS
response.addHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");