简体   繁体   English

在“浏览器刷新”上加载特定页面。 SPA AngularJS

[英]Loading the specific page on Browser Refresh. SPA AngularJS

I am creating a new Web API and Angular application. 我正在创建一个新的Web API和Angular应用程序。 I want to know how we can handle routes on server side. 我想知道我们如何处理服务器端的路由。 Everything is working fine. 一切正常。 I am using ui-router for routing, when i refresh browser that its giving me. 当我刷新浏览器给我的时候,我正在使用ui-router进行路由。

HTTP Error 404.0 - Not Found HTTP错误404.0-找不到

I want to know how we can handle this. 我想知道我们该如何处理。

Code for ui-router ui-router的代码

$stateProvider.state('login', {
    url: '/',
    templateUrl: templatesDirectores.wmAccount + 'login.html',
    controller: 'login-controller',
    controllerAs: 'vm'
})
    .state('register', {
    url: '/register',
    templateUrl: templatesDirectores.wmAccount + 'register.html',
    controller: 'register-controller',
    controllerAs: 'vm'
})
    .state('forgetPassword', {
    url: '/forgetpassword',
    templateUrl: templatesDirectores.wmAccount + 'forget-password.html',
    controller: 'forget-password-controller',
    controllerAs: 'vm'
})

The view is loading fine as per the configuration, but when the URL is localhost:1235/register , it's loading fine first time but when I hit the refresh button I get 404 error. 根据配置,该视图加载良好,但是当URL为localhost:1235/register ,它第一次加载良好,但是当我单击“刷新”按钮时,出现404错误。

This is occurring because you are using HTML5Mode = true in your Angular Application. 发生这种情况是因为您在Angular应用程序中使用HTML5Mode = true Angular uses "hash" ( /#register ) routes to handle it's routing by default, in order to ensure that the browser does not perform a page reload from the server. Angular默认使用“哈希”( /#register )路由来处理其路由,以确保浏览器不会从服务器执行页面重新加载。

Using HTML5Mode , you can suppress the # , but at a cost. 使用HTML5Mode ,您可以取消# ,但要付出一定的代价。 The browser must be HTML5 compliant, because HTML5Mode uses HTML Push State ( HistoryAPI ). 浏览器必须符合HTML5,因为HTML5Mode使用HTML推送状态( HistoryAPI )。

Also, your server must be configured to handle requests for routes which may exist in Angular but do not exist on the server. 另外,您的服务器必须配置为处理可能在Angular中存在但在服务器上不存在的路由请求。 When you directly load a page, either by typing it in or by using refresh, a request is sent to the server, with a URL that the server may not know how to handle. 当您通过键入页面或使用刷新直接加载页面时,会将请求发送到服务器,并带有服务器可能不知道如何处理的URL。 Your server should be configured to return your Index.html page for any routes it does not expressly handle. 您的服务器应配置为针对未明确处理的任何路由返回Index.html页面。 This configuration varies per server . 此配置因服务器而异

Given you stated you are using IIS to host your site, something like the following would be necessary: 假设您说过要使用IIS来托管站点,则需要执行以下操作:

Web.config: Web.config文件:

<system.webServer>
  <rewrite>
    <rules> 
      <rule name="Main Rule" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />                                 
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

Essentially, for all routes ( .* ), if the request is not a file or a directory, rewrite the url to return the base URL / . 本质上,对于所有路由( .* ),如果请求不是文件或目录,请重写url以返回基本URL /

This can also be done in code, something similar to this: 这也可以用代码完成,类似于以下内容:

Global.asax: Global.asax中:

private const string ROOT_DOCUMENT = "/default.aspx";

protected void Application_BeginRequest( Object sender, EventArgs e )
{
    string url = Request.Url.LocalPath;
    if ( !System.IO.File.Exists( Context.Server.MapPath( url ) ) )
        Context.RewritePath( ROOT_DOCUMENT );
}

There are a few other caveats here: 这里还有一些其他警告:

  1. Each platform handles rewrites differently. 每个平台处理重写的方式不同。 In the case of IIS, the URL is rewritten, and the remainder of the route is lost. 在IIS的情况下,URL被重写,并且路由的其余部分丢失。 ie for localhost:1235/register , you will actually load localhost:1235/ , and Angular will never receive the /register route. 即对于localhost:1235/register ,您实际上将加载localhost:1235/ ,而Angular将永远不会收到/register路由。 Essentially, all routes not known by IIS will return your app entry point. 本质上,IIS不知道的所有路由都将返回您的应用程序入口点。

  2. You can set up multiple entry points to your app, but any in-memory references to variables, settings, etc. will be lost when moving from one entry point to another. 您可以为您的应用设置多个入口点,但是当从一个入口点移动到另一个入口点时,所有对变量,设置等的内存引用都将丢失。

Given these two points, you should always consider any external URLs to be a fresh copy of your Angular application, and handle them accordingly. 考虑到这两点,您应该始终将任何外部URL视为Angular应用程序的新副本,并进行相应的处理。

Here's another way to reroute 404's to your SPA: 这是将404重新路由到SPA的另一种方法:

 <system.webServer>
    <httpErrors errorMode="Custom">
      <remove statusCode="404" subStatusCode="-1"/>
      <error statusCode="404" prefixLanguageFilePath="" path="/spa-location.html" responseMode="ExecuteURL"/>
    </httpErrors>
 </system.webServer>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM