angular - 如何在节点服务器上使用 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 文档:
路由应用程序必须回退到 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
推荐阅读
- sql - SQL 查询 - 字符串中任何日期的模式匹配
- c++ - 在运行时解析函数,而不是在编译 C++
- javascript - 有没有办法在 javascript 动态创建的 html 输入中使用 php 变量?
- ios - 将 Swift 结构转换为数据字节
- c++ - 安装 libc++ 的问题
- python - Multiply a 3D matrix with 2D matrix to give a 2D matrix
- bash - 程序如何使用 .bash_profile 添加到 $PATH 变量?
- swift - 如何在 SwiftUI 列表中重新加载数据?
- google-cloud-platform - 为什么整个 CI-CD 过程需要很长时间才能完成?
- azure - 在 docker-compose 中挂载 azure 存储帐户