首页 > 解决方案 > 如何在节点服务器上使用 Angular 运行特定 url(不是主页)而不使用散列?

问题描述

我面临与服务器上的角度路由相关的问题。我使用没有哈希(#)符号的 URL。无哈希: https://localhost:4200/#/activity-details/818659/false 无哈希: https://localhost:4200/activity-details/818659/false

它在本地工作正常,但在节点服务器上部署后显示错误“无法获取 /activity-details/818659/false”

使用哈希它可以正常工作,但我想在 url 中没有哈希的情况下这样做。

没有我正在使用的哈希:导入:[RouterModule.forRoot(routes)]

哈希我正在使用导入:[RouterModule.forRoot(routes),{usehash: true}],

它在服务器端处理吗?如何?它在路由中处理吗?如何?

标签: angular

解决方案


根据Angular 文档

路由应用程序必须回退到 index.html
如果应用程序使用 Angular 路由器,您必须将服务器配置为在请求它没有的文件时返回应用程序的主机页面 (index.html)。静态服务器在收到对http://www.example.com/
的请求时通常会返回 index.html 。但它拒绝http://www.example.com/heroes/42并返回 404 - Not Found 错误,除非它被配置为返回 index.html。


如果您运行完全静态的服务器,则会产生错误,因为服务器上不存在搜索页面。例如,使用Express.js可以捕获这些请求并返回 index.html 文件。

app.post(...)
app.get(...)
app.use((req, res) => res.sendFile(path.join(__dirname, "public/index.html")))


静态服务器配置:

Nginx:

try_files $uri $uri/ /index.html;

Firebase 托管:

"rewrites": [ {
  "source": "**",
  "destination": "/index.html"
} ]

阿帕奇:

RewriteEngine On
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]

# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html

推荐阅读