Issue
I tried to make post-request to my server from iOS device (iOS emulator inside Xcode). I'm using ionic 5 and VueJS and @capacitor-community/http. So my code looks like:
methods: {
async submitForm(){
const form_data = this.$store.getters.my_data;
const options = {
url: 'https://my_domain.com/api/page.php',
headers: {"Content-Type": "application/json"},
data: form_data,
};
await Http.post(options)
.then(res => {
if (res.status === 200) {
console.log(res.data)
}
})
.catch((err) => {
console.log(err)
});
}
I have no submit buttons and I'm not using prevent in the method
When I run my project in the web to testing - I have no problems. GET and POST requests works fine (when testing as web-app I have to remove headers: {"Content-Type": "application/json"} for prevent CORS problems).
So, next I run:
ionic build
npx cap copy
Then I try android emulator (inside android-studio). And my app also works great (all types of requests). Builded android app works perfect on real devices too.
But when it comes to iOS... GET request works fine, as expected. But when I press button which initialize POST request - nothing happens! No errors... No alerts... No logs... Just nothing. My backend doesn't get any request. I have no idea what to do.
There are lines in my Info.plist:
<key>WKAppBoundDomains</key>
<array>
<string>www.my_domain.com</string>
<string>https://my_domain.com</string>
</array>
TransportSecurity flag set as TRUE:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
I tried use native fetch, but the result is same - nothing happens.
So I think it is kind of problems with iOS, but I haven't enough knowledges to understand what the problem is.
Solution
So, a few days I tried to realize what's wrong with my code. Finally I found some logs which says:
Unhandled Promise Rejection: DataCloneError: The object can not be cloned.
It means that something wrong with my data I trying to send.
And the reason is:
const form_data = this.$store.getters.my_data;
This line returns not a json object but some Proxy object. The behavior is pretty similar to json: you can use form_data.name or any other values, but swift for some reasons can't use this object.
So, we need just to create new json object for using in post body:
async submitForm(){
const form_data = this.$store.getters.my_data;
const body_data = {};
for (const [key, val] of Object.entries(form_data)) {
body_data[key] = val;
}
const options = {
url: 'https://my_domain.com/api/page.php',
headers: {"Content-Type": "application/json"},
data: body_data,
};
await Http.post(options)
.then(res => {
if (res.status === 200) {
console.log(res.data)
}
})
.catch((err) => {
console.log(err)
});
}
And this code works fine
P.S. be sure that all you values in body_data are standard JS types
Answered By - DevilSAM
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.