直接浏览到路由地址或刷新时,Angular2无法加载 [英] Angular2 not loading when directly browsed to route address or on refresh

查看:98
本文介绍了直接浏览到路由地址或刷新时,Angular2无法加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在应用程序中定义了一条路由:

In the application there is a route defined:

const routes: Routes = [
  { path: '', component: MainComponent },
  { path: 'users', component: UsersComponent }
]

在index.html中,基本href也已正确定义.

In index.html the base href is also correctly defined.

<base href="/">

在应用程序中导航时,路由会正确加载.但是,当用户直接通过浏览器输入 .../users 时,不会加载该应用程序并返回404.同样,当用户刷新网页(F5)时,也不会加载该应用程序.

When navigating through application the routes are loaded correctly. But when users enters .../users directly through the browser the application is not loaded and returns 404. Also when the users refresh the webpage (F5), the application is also not loaded.

角度代码或服务器配置是否存在问题?

Is there something wrong with angular code or server configuration?

推荐答案

这取决于您的服务器设置.您需要设置到 index.html 的重定向,以了解何时发生404,

It depends on your server setup. You need to either set up a redirect to index.html for when a 404 occurs,

或设置一个重写,以便某个路径之后的每个请求始终导致 index.html

Or set up a rewrite so that every request after a certain path always leads to index.html,

或者简单地将位置策略更改为哈希而不是HTML5(尽管出于某些原因我不建议这样做,正如Peter所说).

Or simply change the location strategy to hash instead of HTML5 (although not what I'd recommend for a few reasons, as Peter said).

这篇关于直接浏览到路由地址或刷新时,Angular2无法加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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