【问题标题】:Angular 2 in production URLs are breaking when reloading the page重新加载页面时,生产 URL 中的 Angular 2 中断
【发布时间】:2017-11-11 08:27:35
【问题描述】:

当我加载应用程序并重定向到另一个路由时,我正在使用 Nginx 服务器在生产中运行我的应用程序,它工作正常,但是当我重新加载页面时,我收到 404 Not Found 错误。 考虑如果我在www.example.com 加载应用程序,那么在重新加载页面后路由也可以正常工作。

如果我首先重定向到另一条路由 www.example.com/about,则页面正在加载,但如果我在相同状态下重新加载页面,则会收到错误 404 Not Found。

我找到了相同的解决方案

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}
]);

上述解决方案工作正常,但问题是我正在获取带有 # 的 URL

www.example.com/#
www.example.com/#/about

但我的要求是我不想在 URL 中出现#

即使我在 Nginx .config 文件中进行了更改,如下所示

  location /subfolder/myapp/ {
    try_files $uri /subfolder/myapp/index.html;
}

但 URL 仍然出现相同的错误

请大家帮忙,谢谢

【问题讨论】:

  • 我认为this topic 可能会对您有所帮助。很抱歉没有在这方面提供更大的帮助。
  • @nvkfr 我尝试了此链接中给出的解决方案,但它的 HashLocationStrategy 在链接 www.example.com/#/about 中给出了 # 这是我的问题。

标签: javascript angular typescript build angular-routing


【解决方案1】:

试试这个...

index index.html;

location / {
  try_files $uri $uri/ /index.html;
}

# Location of asset folder
location ~ ^/(assets)/  {
  gzip_static on;
  gzip_types image/svg+xml text/plain text/xml text/css
    text/comma-separated-values
    text/javascript application/x-javascript
    application/atom+xml;

  expires 0;
}

【讨论】:

  • 在我的项目中没有资产目录
  • 抱歉,假设是使用 Angular CLI。尽管如此,如果没有资产位,这可能/应该会有所帮助。
  • 你能解释一下上面的代码是如何处理路由的吗
  • 我可以尝试,但我不会做到公正。这个答案肯定会更好stackoverflow.com/a/17800131/5076023 但基本上我们会将所有流量引导到index.html 并允许角度应用程序查看 url 并呈现出适当的路线本身。
猜你喜欢
  • 2019-01-28
  • 2020-11-09
  • 2018-05-09
  • 2017-08-23
  • 1970-01-01
  • 2017-11-22
  • 2023-02-05
  • 2017-07-27
  • 2011-09-16
相关资源
最近更新 更多