为Angular 2配置history.pushState

Jan*_*sen 5 angular2-routing angular2-cli angular

我的Angular 2应用程序使用默认的HTML 5 history.pushState 位置策略.如何使用history.pushState浏览器刷新配置服务器并且浏览器URL不生成404s?

例如,Tour of Heroes应用程序有一些不同的应用程序路径,例如:

http://localhost:8080/dashboard
http://localhost:8080/heroes
http://localhost:8080/detail/13
Run Code Online (Sandbox Code Playgroud)

如果你打刷新在这些航线上的一个,或键入一个URL,你会得到404,因为/detail/13是一个应用程序的路线,而不是服务器资源.我已将位置策略配置head在我的顶部index.html:

<!doctype html>
<html>
<head>
  <base href="/">
  <meta charset="utf-8">
  <title>Tour of Heroes</title>
Run Code Online (Sandbox Code Playgroud)

但是如何配置服务器以便将所有URL发送到我的应用程序而不是生成404

注意:这个问题是问题的补充当我通过浏览器刷新Angular 2:404错误时,Angular 2.0路由器无法重新加载浏览器,询问如何解决此问题.对于Firebase,有这样的:当我刷新我的网站时,我得到一个404.这是使用Angular2和firebase,对于Apache,这就是:Angular路由的htaccess重定向.

Jan*_*sen 7

nginx的

要使用nginx:

/etc/nginx/ngin.conf

location / {
    root   /home/jan/tour-of-heroes/;
    index  index.html index.htm;
}

error_page 404 =200 /index.html;
Run Code Online (Sandbox Code Playgroud)
  • 支持 history.pushState
  • 生产HTTP服务器

pushState的服务器

要使用pushstate-server:

pushstate-server /home/jan/tour-of-heroes
Run Code Online (Sandbox Code Playgroud)
  • 支持 history.pushState
  • 生产HTTP服务器

表达

使用快递:

node express.js
Run Code Online (Sandbox Code Playgroud)

其中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);
Run Code Online (Sandbox Code Playgroud)
  • 支持 history.pushState
  • 生产HTTP服务器

HTTP服务器

要使用http-server:

node http-server/bin/http-server /home/jan/tour-of-heroes
Run Code Online (Sandbox Code Playgroud)
  • 没有 history.pushState
  • 生产HTTP服务器

直播服务器

要使用实时服务器:

live-server --entry-file=index.html /home/jan/tour-of-heroes
Run Code Online (Sandbox Code Playgroud)
  • 支持 history.pushState
  • 开发 HTTP服务器

服务

使用ng服务:

ng serve -prod
Run Code Online (Sandbox Code Playgroud)

或者提前编译:

ng serve -prod -aot
Run Code Online (Sandbox Code Playgroud)
  • 支持 history.pushState
  • 生产应用程序构建
  • 开发 HTTP服务器