shwld
Invalid Date

CapacitorでCORSをどうすればよいか考えた

Capacitorから自分のAPIサーバーへのリクエストがCORSでブロックされた。当然といえば当然だろう

サーバー側のCORS設定を緩めたくはないがどうすればいいのか。考えた

CapacitorでOriginは以下のように設定されるようだ

  • iOScapacitor://localhost
  • Androidhttp://localhost

ただし、capacitor.config.tsで上書きできるようで、localhost開けたくないので基本的には上書きしたほうがよいだろう

ts
capacitor.config.ts
{
  server: {
    hostname: 'www.g-g-g-g.games'
  }
}

これを変えたところ、Originはちゃんと変わっていることがログで確認できたがschemaがhttp://だった

log
2021-09-18 08:48:15.110 13215-13215/app.shwld.g4note E/Capacitor/Console: File: http://www.g-g-g-g.games/select_character - Line 0 - Msg: Access to fetch at 'https://hoge-server/graphql' from origin 'http://www.g-g-g-g.games' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

schemaを変えるオプションがあったので指定してみた

ts
capacitor.config.ts

  server: {
    hostname: 'www.g-g-g-g.games',
    androidScheme: 'https', // <- add
  },

httpsに変わった。存在するurlになってしまったのか、アプリ起動時に https://www.g-g-g-g.gamesが開いたw

また、iOSの場合、schemaにhttpなどは指定できないようだ。デフォルトcapacitorが設定されるようだ。

CORS的にはschemaにhttps以外を通すようにすれば問題なさそうなので、iOS/AndroidのOriginを統一すべく一旦それで行くことにしたい...

ts
capacitor.config.ts
  server: {
    hostname: 'www.g-g-g-g.games',
    androidScheme: 'capacitor', // <- modify
  },

CORS エラー - イオンドキュメント (ionicframework.com)

https://ionicframework.com/docs/troubleshooting/cors

書いた人

shwld
shwldLV: 106
ATK32620
DEF30929
SPD38392
HIT95
AVD19
CRI20

他の投稿を見る

もっと見る