【问题标题】:Refreshing same URL gives 404 not found in angular刷新相同的 URL 会导致 404 在 Angular 中找不到
【发布时间】:2020-07-02 22:23:07
【问题描述】:

我在服务器上托管了我的 Angular 应用程序。当我单击服务器 url 时,它会将我重定向到登录页面。但是,当我刷新以登录为后缀的相同 url 时,它给了我 404 not found 错误。 给出的原始 url 没有登录后缀。 请帮忙。

在 app.routing.module.ts 中,我已经配置了这样的路由器路径:

【问题讨论】:

  • 您需要配置您的网络服务器:angular.io/guide/deployment
  • 提供的答案有效吗?
  • 是的,它有效。谢谢卢卡斯。

标签: angular http-status-code-404 angular8


【解决方案1】:

Angular 有时会发生这种情况。我已经看到了发生这种情况的几个不同原因。一个是因为 URL 更改使用简单的 js 发生,并且还阻止网络爬虫,因为给定链接上没有内容。无论如何,如果您想要快速修复,您可以使用哈希方法。这种方法将使您的链接看起来像这样: http://link/#/pagehttp://link/page 相比(注意 #

选项 1

在您的 app.module.ts 中,为 HashLocationStrategy, LocationStrategy 添加导入:

import { HashLocationStrategy, LocationStrategy } from '@angular/common'; ,然后在你的 NgModule Provider 中:

{provide: LocationStrategy, useClass: HashLocationStrategy}

这可能类似于以下内容:

App.Module.Ts

import { NgModule }       from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
import { HashLocationStrategy, LocationStrategy } from '@angular/common';

@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule],
    providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
    bootstrap: [AppComponent],
})
export class AppModule {}

选项 2

另一种方法是使用 RouterModule.forRoot...useHash: true arg。

在您的路由模块或应用模块中:

@NgModule({
  imports: [
    ...
    ...
    RouterModule.forRoot(routes, { useHash: true })
  ],

选项 3

如果这些不起作用,或者它们没有给您想要的结果(您可能不想要 has 方法),那么我建议您研究 AngularUniversal,或研究服务器端方法来配置您的服务器以提供服务index.html 文件用于定义的每个路由。这是一种更长更复杂的方法,但希望上述选项就足够了。

【讨论】:

  • 选项 1 适用于我在 IIS 上的 angular 12
  • 选项 2:{ useHash: true } 为我工作。谢谢
  • 选项 2 也适用于我(Angular 12),谢谢
猜你喜欢
  • 1970-01-01
  • 2018-11-27
  • 2019-01-10
  • 1970-01-01
  • 1970-01-01
  • 2018-05-03
  • 2020-07-21
  • 1970-01-01
  • 2017-06-24
相关资源
最近更新 更多