Adam
Adam

Reputation: 615

Cors in capacitor for android

I want to convert my angular web app to mobile app. I understand how works cors in web, there is just need to set port in frontend and the same port and url in backend allowedOrigins settings. But I can't understand how does work cors in mobile app because IP is different in each mobile device, not static like in frontend.

I can config in my computer something like this:

In server:

app:
  auth:
  cors:
    allowedOrigins: http://127.0.0.1:8100,

In mobile app (capacitor.config.ts):

import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
  appId: 'com.my.app',
  appName: 'my-mobile',
  webDir: 'dist/my-mobile',
  bundledWebRuntime: false,
  server: {
    cleartext: true,
    hostname: '127.0.0.1:8100',
  }
};

export default config;

And this works, but in locale, how to do it in prod, on real android devices?

Upvotes: 3

Views: 6900

Answers (2)

Chen Peleg
Chen Peleg

Reputation: 2114

I had the same cors promblem and the reason was that I didn't use the Capacitor HTTP plugin. Added this to the capacitor.config.ts:

// capacitor.config.ts (or js)

const config  = {
   ...
   plugins: {
     ...
     CapacitorHttp: {
        enabled: true,
     }, 
   }, 
};

This is part of the core library so no need to install anything.

Upvotes: 1

Adam
Adam

Reputation: 615

I got answer here https://forum.ionicframework.com/t/how-works-cors-in-capasitor-on-real-devices/230474

In prod, the apps run at the following URL/origin by default:

iOS: capacitor://localhost Android: http://localhost So, both of those need to be configured in your backend as allowed origins. You could also use Capacitor’s HTTP plugin to get around CORS all together.

Upvotes: 1

Related Questions