Home > database >  Failed to send post request with Capacitor (works fine from regular webpage)
Failed to send post request with Capacitor (works fine from regular webpage)

Time:03-21

I'm working on an app using Ionic (Vue) and have already set a server side (Python with FastAPI).

While I've no issues sending a request when running my app on the browser (ionic serve), I fail to do so when running it on iOS simulator.

I've tried both axios and Capacitor HTTP library and the outcomes are the same. Below are only the relevant parts from client:

<template>
<base-layout page-title="Choose Players" page-default-back-link="/home">
  <ion-item v-for="contact in contacts" :key="contact.phoneNumbers[0]" @click="toggleContact(contact)">
    <ion-icon v-if="isContactSelected(contact)" slot="end" :icon="checkmark"/>
    {{ contact.displayName }}
  </ion-item>
  <ion-button expand="block" @click="inviteSelectedContacts">Invite Selected Contacts</ion-button>
</base-layout>
</template>

<script>
import { IonItem, IonIcon, IonButton } from "@ionic/vue";
import { checkmark } from 'ionicons/icons';
import { Contacts } from "@capacitor-community/contacts";
import { serverURL } from '@/components/Config';
// import axios from 'axios';
import { Http } from '@capacitor-community/http';


export default {
  name: "AddPlayers",

  

  data() {
    return {
      contacts: [],
      chosenContacts: new Set()
    };
  },

  methods: {
    
    async inviteSelectedContacts() {
      let data = {userId: 'test id', users: this.chosenContacts}
      let url = `${serverURL}/inviteUsers`;
      try {
        let options = {url: url, data: data}
        let res = await Http.post(options);
        if (res.status === 200){
          alert(res.status)
        }
        return res.data
      }
      catch (err) {
        alert(err);
      }
    }
  },

My conclusion is that it's somehow related to CORS not being defined properly for Capacitor only (as they're working just fine for the browser), but I couldn't understand where should I define those.

The server API url is http://fastapi.localhost:8008

Update: I was able to log and view the error (via Xcode):

[log] - {"message":"Network Error","name":"Error","stack":"createError@\nhandleError@","config":{"transitional":{"silentJSONParsing":true,"forcedJSONParsing":true,"clarifyTimeoutError":false},"transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"maxBodyLength":-1,"headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json"},"method":"post","url":"http://fastapi.localhost:8008/inviteUsers","data":"{\"userId\":\"test id\",\"users\":{}}"},"status":null}

CodePudding user response:

Too much time wasted on this one...

It turns out that the solution was to change the development server URL to an IP based one: http://127.0.0.1:8008 (in my case).

I don't know why Capacitor doesn't accept DNS naming.

I was able to verify it by adding this dummy endpoint to my server:

from fastapi import FastAPI, Request
...
@app.post("/dummypath")
async def get_body(request: Request):
    return await request.json()

so now from the client:

async inviteSelectedContacts() {
  // let data = {userId: 'test id', users: this.chosenContacts}
  let data = {}
  let url = `${serverURL}/dummypath`;
  try {
    let res = await axios.post(url, data);
    if (res.status === 200){
      alert(res.status)
    }
    alert(res);
    return res.data
  }
  catch (err) {
    console.log(err);
    alert(err);
  }
}

where serverURL is http://127.0.0.1:8008

  • Related