通过浏览器刷新时,出现Angular 2:404错误 [英] Angular 2: 404 error occur when I refresh through the browser
问题描述
我是Angular 2的新手.我已将单页应用程序存储在服务器中名为"myapp"的文件夹中.我已将基础中的URL更改为 http://example.com/myapp/`.
I'm new to Angular 2. I have stored my single-page application in my server within a folder named as "myapp". I have changed the URL in the base to http://example.com/myapp/`.
我的项目有两个页面.所以我实现了Angular 2路由.我将默认页面设置为登录名.当我在浏览器中键入http://example.com/myapp/
时,它将自动重定向到http://example.com/myapp/login
.但是,如果刷新该页面,则会出现404
错误,并说未找到http://example.com/myapp/login
.
My project have two pages. So I implement Angular 2 routing. I set the default page as login. When I type http://example.com/myapp/
in my browser it will redirect automatically to http://example.com/myapp/login
. But if refresh that page I get a 404
error, saying that http://example.com/myapp/login
is not found.
但是,如果我使用lite服务器运行项目,则一切正常.在这种情况下,index.html中的URL将为"/"
.如何解决?
But if I run my project using the lite server everything is working. In this case base the URL in index.html will be "/"
. How do fix it?
推荐答案
实际上,刷新应用程序时会出现404错误,这是正常的,因为浏览器中的实际地址正在更新(并且不使用#/hashbang方法).默认情况下,HTML5历史记录用于在Angular2中重复使用.
In fact, it's normal that you have a 404 error when refreshing your application since the actual address within the browser is updating (and without # / hashbang approach). By default, HTML5 history is used for reusing in Angular2.
要解决404错误,您需要更新服务器以为定义的每个路由路径提供index.html
文件.
To fix the 404 error, you need to update your server to serve the index.html
file for each route path you defined.
如果要切换到HashBang方法,则需要使用以下配置:
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, HashLocationStrategy} from '@angular/common';
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 (but you will have a #
in your address).
This link could help you as well: When I refresh my website I get a 404. This is with Angular2 and firebase.
希望它对您有帮助, 蒂埃里
Hope it helps you, Thierry
这篇关于通过浏览器刷新时,出现Angular 2:404错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!