我的Angular 2应用程序使用默认值HTML 5 history.pushState location strategy . 如何使用 history.pushState
配置服务器,以便浏览器刷新并且浏览器URL不会生成 404
?
例如,Tour of Heroes应用程序有一些不同的应用程序路径,如:
http://localhost:8080/dashboard
http://localhost:8080/heroes
http://localhost:8080/detail/13
如果您在其中一个路由上点击刷新,或者键入其中一个URL,您将获得 404
,因为 /detail/13
是应用程序路由,而不是服务器资源 . 我在 index.html
中的 head
顶部配置了位置策略:
<!doctype html>
<html>
<head>
<base href="/">
<meta charset="utf-8">
<title>Tour of Heroes</title>
但是如何配置服务器以便将所有URL发送到我的应用程序而不是生成 404
?
Note :这个问题是问题的补充Angular 2 : 404 error occur when i refresh through Browser和Angular 2.0 router not working on reloading the browser要求 how 来解决这个问题 . 对于Firebase,有这样的:When I refresh my website I get a 404. This is with Angular2 and firebase,对于Apache,就是:htaccess redirect for Angular routes .
2 回答
nginx
要使用nginx:
/etc/nginx/ngin.conf
支持
history.pushState
生产环境 HTTP服务器
pushstate-server
要使用pushstate-server:
支持
history.pushState
生产环境 HTTP服务器
快递
要使用express:
其中
express.js
:支持
history.pushState
生产环境 HTTP服务器
http-server
要使用http-server:
no
history.pushState
生产环境 HTTP服务器
live-server
要使用live-server:
支持
history.pushState
开发HTTP服务器
ng服务
要使用ng serve:
或者ahead-of-time compilation:
支持
history.pushState
生产环境 应用程序构建
开发HTTP服务器
使用最新的angular-cli版本创建项目,他们将beta.10和beta.14之间的构建系统从SystemJS更改为Webpack .
在
app.module.ts
中使用 LocationStrategy and HashLocationStrategy 类,如下面的代码示例所示 . 当您将应用程序部署到任何http服务器(nginx)时,它将解决您在任何特定路由上的刷新问题 .将这些类添加到providers部分后,运行
ng serve
,您的应用程序root将在浏览器中看起来像http://localhost:4200/#/
.刷新时,它会在适当的位置重新加载 .
另请查看Angular 2.0 router not working on reloading the browser以获取更多信息 .
希望有所帮助!