AngularDartでリロードに対応する

Categories
Tags
Share

AngularDartでルーティングができるようになったからOK!と思って画面をリロードしたら404 Not foundが出てしまいました。 pub serveで起動した場合、LocationStorategyのPathLocationStorategyに対応していないみたいで、別途リバースプロキシを立てて対応しなければならないようです。 またHashLocationStorategyを使う方法もあるみたいだったのですが、設定してみてもうまく動きませんでした。多分設定内容が悪いんだと思います。

参考にしたのは、Qiitaの記事なので、そちらを読んだ方がいいと思いますが、もしそちらが消えたら自分が困るのでここにも記しておきます。

以下、読みたい人だけ読んでください。

リバースプロキシサーバを立てる

リバースプロキシにはnginxを使いました。 Macなのでhomebrewで入れます。

brew update
brew install nginx

AngularDartプロジェクトのディレクトリでnginx.confを作ります。

# nginx.conf on reverse proxy for local SPA dev.
# Nginx installed by macOS Homebrew.
# Please rewrite paths and ports for your dev env.

# Start: nginx -c $PWD/nginx.conf
# Stop: nginx -s stop

events {}

http {
    include       /usr/local/etc/nginx/mime.types;
    default_type  application/octet-stream;

    access_log  /usr/local/var/log/nginx/access.log;
    error_log  /usr/local/var/log/nginx/error.log;

    # SPA dev server. On Dart web dev, it is usually pub dev server.
    upstream spa {
        server localhost:9910;
    }

    server {
        listen       9900;
        server_name  localhost;

        # Any files with extension.
        location ~ .+\.[^.]+$ {
            proxy_pass http://spa;
        }
        # Fall back to a entry point for bootstrapping SPA with pushState mode (a.k.a html5 mode called in Angular1).
        location / {
            proxy_pass http://spa;
            try_files $uri /index.html;
        }
    }
}

そして、nginxを起動します。

nginx -c $PWD/nginx.conf

AngularDart側の設定

AngularDart側は、ルーティングを使うときに設定しますが、index.htmlにbase urlを設定します。

<head>
  <!-- metaタグなど省略 -->
  <base href="/">
  <!-- css読込など省略 -->
</head>

SPA pushState routingの確認

nginx.confで、リバースプロキシサーバは9900番ポートで、AngularDartのサーバを9910番ポートで起動するように設定しているので、 起動時に9910番を指定します。

pub serve --port 9910

これでOK。Chromiumで http://localhost:9900 にアクセスし、ルーティングされたページに移動後に画面をリロードしても404にならないことを確認してみましょう!


comments powered by Disqus