When I refresh my website I get a 404. This is with Angular2 and firebase

删除回忆录丶 提交于 2019-11-26 17:44:40

For Firebase Hosting the documentation on redirects and rewrites is here: https://www.firebase.com/docs/hosting/guide/url-redirects-rewrites.html

From there:

Use a rewrite when you want to show the same content for multiple URLs. Rewrites are particularly useful with pattern matching, as you can accept any URL that matches the pattern and let the client-side code decide what to display.

You're likely looking for the first rewrite sample on that page:

"rewrites": [ {
  "source": "**",
  "destination": "/index.html"
} ]

This is an instruction for the web server to serve /index.html for any incoming request, no matter what the path is.

I think that you use the default mode of Angular2 routing (i.e. HTML5LocationStrategy). In this case, you need some configuration on your webserver to make load the index.html (your entry point file) for each URLs corresponding to each routes.

If you want to switch to the HashBang approach, you need to use this configuration:

import {bootstrap} from 'angular2/platform/browser';
import {provide} from 'angular2/core';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {LocationStrategy, Location, HashLocationStrategy } from 'angular2/router'; 

import {MyApp} from './myapp';

bootstrap(MyApp, [
  ROUTER_PROVIDERS,
  provide(LocationStrategy, {useClass: HashLocationStrategy}
]);

In this case, when you refresh the page, it will be displayed again.

Hope it helps you, Thierry

Viktor Hardubej

I had the same issue on production. The following steps helped me to fix the problem. You have to add in your root module next:

imports: [RouterModule.forRoot(routes, {useHash: true})]

and it will swich to HashLocationStrategy. Angular documentatation

Hope it will help someone !!

Expanding on the accepted answer I wanted to show that the rewrites rules go inside of the hosting rules. in the firebase.json

"hosting": {
  "rewrites": [ {
    "source": "**",
    "destination": "/index.html"
   } ]
}

Firebase also has an updated docs page where the above example is from.

Also, I was thrown off by the hash (#) question around this. I found that doesn't apply to the new Angular. Making these small changes in the firebase.json, rebuilding, publishing to firebase, and then doing a refresh page with clear-cache immediately resolved my 404 issue with no workarounds required for hashes in the URL.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!