Angular 2:通过浏览器刷新时出现 404 错误 [英] Angular 2: 404 error occur when I refresh through the browser

查看:24
本文介绍了Angular 2:通过浏览器刷新时出现 404 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Angular 2 的新手.我已将我的单页应用程序存储在我的服务器中名为myapp"的文件夹中.我已将 base 中的 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 has 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 the base 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).

此链接也可以帮助您:当我刷新我的网站时,我得到一个 404.这是使用 Angular2 和 firebase.

This link could help you as well: When I refresh my website I get a 404. This is with Angular2 and firebase.

希望对你有帮助蒂埃里

这篇关于Angular 2:通过浏览器刷新时出现 404 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆