capacitor-community / http

Community plugin for native HTTP
MIT License
209 stars 136 forks source link

POST request with JSON not working on iOS-devices #207

Closed DevilSAM closed 2 years ago

DevilSAM commented 2 years ago

Describe the bug Hi everyone! I tried to make post-request to my server from iOS device (iOS emulator inside Xcode). I'm using ionic 5 and VueJS. 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;t get any request. I have no idea what to do.

There are lines in my Info.plist:

<key>WKAppBoundDomains</key>
<array>
    <string>www.mydomain.com</string>
    <string>https://mydomain.com</string>
</array>

Expected behavior iOS-device send post-request with json data to my server.

I hope you will be able to help me with that problem :)

DevilSAM commented 2 years ago

The problem was in the const form_data = this.$store.getters.my_data; It returns Proxy object Swift can't convert this to native language. To solve this problem we need just create simple json object to pass in the post request

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 no it works :)