为 Angular 2 配置 history.pushState [英] Configure history.pushState for Angular 2
问题描述
我的 Angular 2 应用程序使用默认的 HTML 5 history.pushState
定位策略.如何使用 history.pushState
配置服务器,以便浏览器刷新和浏览器 URL 不会生成 404
s?
My Angular 2 application uses the default HTML 5 history.pushState
location strategy. How do I configure a server with history.pushState
so browser refreshes and browser URLs do not generate 404
s?
例如,Tour of Heroes 应用程序有几个不同的应用程序路线,例如:>
For example, the Tour of Heroes application has a few different application routes like:
http://localhost:8080/dashboard
http://localhost:8080/heroes
http://localhost:8080/detail/13
如果您在这些路由之一上刷新,或输入其中一个 URL,您将得到 404
,因为 /detail/13
是一个应用程序路由,而不是服务器资源.我已经在我的 index.html
中的 head
顶部配置了位置策略:
If you hit refresh on one of these routes, or type one of the URLs, you'll get 404
since /detail/13
is an application route, not a server resource. I've configured the location strategy at the top of the head
in my index.html
:
<!doctype html>
<html>
<head>
<base href="/">
<meta charset="utf-8">
<title>Tour of Heroes</title>
但是应该如何配置服务器才能将所有 URL 发送到我的应用程序而不是生成 404
?
but how should a server be configured so it sends all URLs to my application instead of generating a 404
?
注意:这个问题是对问题的补充 Angular 2 : 404当我通过浏览器刷新和Angular 2.0 路由器无法重新加载浏览器,询问如何解决此问题.对于 Firebase,有这个:当我刷新我的网站时,我得到一个 404.这是 Angular2 和 firebase 和 Apache 有这个:Angular 路由的 htaccess 重定向.
Note: This question is the complement to the questions Angular 2 : 404 error occur when i refresh through Browser and Angular 2.0 router not working on reloading the browser asking how to address this problem. For Firebase, there's this: When I refresh my website I get a 404. This is with Angular2 and firebase and for Apache there's this: htaccess redirect for Angular routes.
推荐答案
nginx
要使用 nginx:
/etc/nginx/ngin.conf
location / {
root /home/jan/tour-of-heroes/;
index index.html index.htm;
}
error_page 404 =200 /index.html;
- 支持
history.pushState
- 生产 HTTP 服务器
pushstate-server /home/jan/tour-of-heroes
- 支持
history.pushState
- 生产 HTTP 服务器
要使用express:
node express.js
其中 express.js
:
var express = require('express'),
path = require('path'),
port = process.env.PORT || 8083,
app = express();
app.use(express.static(__dirname ));
app.get('*', function(request, response){
response.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(port);
- 支持
history.pushState
- 生产 HTTP 服务器
使用http-server:
node http-server/bin/http-server /home/jan/tour-of-heroes
- 否
history.pushState
- 生产 HTTP 服务器
要使用live-server:
live-server --entry-file=index.html /home/jan/tour-of-heroes
- 支持
history.pushState
- 开发 HTTP 服务器
- supports
history.pushState
- development HTTP server
要使用ng serve:
ng serve -prod
或使用提前编译:
ng serve -prod -aot
- 支持
history.pushState
- 生产应用构建
- 开发 HTTP 服务器
- supports
history.pushState
- production application build
- development HTTP server
这篇关于为 Angular 2 配置 history.pushState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!