LoginSignup
3
5

More than 5 years have passed since last update.

[Ionic] Service Proxies を使うプロジェクトをネイティブビルドするとHTTPリクエストが動作しない問題

Posted at

環境

  • Ionic 3.19.1

WebApp等から別ドメインのAPIを直接叩くと、CORS制約に引っかかってリソースを取得できないことがあります。
Ionicでは、Service Proxiesを設定することで、このCORS制約を回避することができます。

Ionicの素振りとしてGitHub Event WatcherというWebAppを作ったのですが、このアプリ内では GitHub のユーザーイベントを取得するAPIを叩く際にService Proxiesを使用しています。
プロキシの設定は以下です。

ionic.config.json
  ...
  "proxies": [
    {
      "path": "/github",
      "proxyUrl": "https://api.github.com"
    }
  ]
  ...

また、APIを叩くコードはこんな感じです。

src/providers/events/events.js
  ...
  constructor(
    public http: HttpClient,
  ) {
  }
  ...
  getEvents(username: string): Observable<Object> {
    const url = `users/${username}/events`;
    return this.http.get(`/github/${url}`);
  }
  ...

しかし、CORSはWebアプリ上の制約であり、ネイティブアプリには関係ありません。

Cordovaでビルドしたネイティブアプリからだと、このコードではリクエストを送信できません。
proxiesの設定が無視され、そのまま/github/users/${username}/eventsにリクエストを飛ばしてしまいます。

解決策として、Web/PWAとネイティブで処理を分けます。

src/providers/events/events.js
  ...
  constructor(
    public http: HttpClient,
    public platform: Platform,
  ) {
  }
  ...
  getEvents(username: string): Observable<Object> {
    let url = `/users/${username}/events`;

    if (this.platform.is('mobile')) {
      url = `https://api.github.com/${url}`;
    } else {
      url = `/github/${url}`
    }

    return this.http.get(url);
  }
  ...

これでネイティブの場合は普通に元のURLを叩きに行くようになります。


このように、プラットフォームに依存した処理を書く場合はIonicのPlatform APIを使います。
Platform APIで判定できるプラットフォームの一覧は以下に載っています。

Platform - Ionic API Documentation - Ionic Framework

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5