使用启用 Html5 模式的 Angular Ui 路由器时页面重新加载失败路由器、加载、模式、页面

2023-09-06 08:25:20 作者:别碰我!我有刺

我在我的 Angular 应用程序中使用 Angular UI 路由器,并且我已启用 HTML5 模式,通过在配置中使用 $locationProvider 来删除 URL 中的 #.

I am using Angular UI Router in my angular app and i have enabled HTML5 mode to remove the # form the URL by using $locationProvider in the config.

var app = angular.module('openIDC', ['ui.router']);
app.config(function($urlRouterProvider, $stateProvider, $locationProvider) {

    $locationProvider.html5Mode(true);

    $urlRouterProvider.otherwise('/');

    $stateProvider
    .state('home', {
        url: '/',
        templateUrl: 'views/home.html',
        controller: 'HomeController'
    })
    .state('login', {
        url: '/login', 
        templateUrl: 'views/login.html',
        controller: 'LoginController'
    })
});

我还在 index.html 文件中设置了 <base href="/"/> 标记.路由工作正常,我可以导航到页面并删除 # 但是当我使用浏览器上的重新加载按钮刷新页面时,会出现 404 错误响应.

I have also set the <base href="/" /> tag in the index.html file as well. The routing works fine and i can navigate to pages and the # is removed but when i refresh the page using the reload button on the browser there is a 404 error response.

为什么会发生这种情况,我该如何解决它并启用 HTML5 模式以获得正确的 URL

Why is this happening and how can i fix it and have HTML5 mode enabled to have proper URLs

推荐答案

Kasun,出现这种情况的原因是因为您试图从您的子路由之一刷新页面(与 ui-router 无关).

Kasun, the reason that this is occurring is because you are trying to refresh the page from one of your sub routes (has nothing to do with ui-router).

基本上,如果您请求 www.yourdomain.com/,您的服务器设置可能会返回引导您的 Angular 应用程序的 index.html.应用加载后,任何进一步的 url 更改都会考虑 html5Mode 并通过 ui-router 更新您的页面.

Basically if you request www.yourdomain.com/ you likely have your server setup to return index.html which bootstraps your angular app. Once the app has loaded, any further url changes take html5Mode into consideration and update your page via ui-router.

当您重新加载页面时,角度应用程序不再有效,因为它尚未加载,因此如果您尝试加载子路由(例如:www.yourdomain.com/someotherpage),那么您的服务器不知道如何处理 /someotherpage 并可能返回 404 或其他一些错误.

When you reload your page the angular app is no longer valid as it has not loaded yet, so if you are trying to load a sub route (for example: www.yourdomain.com/someotherpage), then your server does not know how to deal with /someotherpage and likely returns 404 or some other error.

您需要做的是配置您的服务器,以便为 所有 路由返回您的 Angular 应用程序.我主要使用 node/express,所以我做了类似的事情:

What you need to do is configure your server to return your angular app for all routes. I primarily use node/express, so I do something like:

app.get('*', function(req, res, next) {
    // call all routes and return the index.html file here
}

注意:我通常使用这样的东西作为最终的全部,但是我还包括其他路由,例如请求静态文件、网络爬虫和任何其他需要处理的特定路由.