首页 文章

Angular 2 - 如何使页面可刷新?

提问于
浏览
0

拥有唯一的 index.html 物理页面,将多个组件作为虚拟组件提供,其路由设置如下:

{path: 'cat/:name', component: CatComponent}

所以,我可以使用 routingLink="/cat/tom" 轻松访问它的名字 . 但是,如果我刷新页面或在浏览器地址栏中手动键入链接 http://localhost:8080/cat/tom 我收到错误 404 not found .

我知道这是一个常见问题,Angular doc说:

使用此模式需要在服务器端重写URL,基本上您必须重写所有链接到应用程序的入口点(例如index.html)

但它似乎并不那么容易,我在哪里重写网址?我希望通过刷新 /cat/tom 我将获得相同的页面而不是根页面 .

尝试了另一种方法,使用 HashLocationStrategy 而不是默认 HTML5 并使用 nginx 重写了特定资源的URL,如 /#/cat/tom ,因为它们很容易通过直接路径访问,但还有另一个失败 - that's why .

如何使Angular页面可刷新? nginx 是那里的球员吗?

1 回答

  • 0

    嗯,现在确实有效 .

    现在可以刷新虚拟位置 /cat/tom/cat/bob ,或通过直接URL访问它 . 刷新页面赢了't lose it' s url并且不会抛出 404 not found 错误 .

    Nginx conf:

    server {
        listen       80;
        server_name  localhost;
        root /;
    
        #charset koi8-r;
    
        #access_log  logs/host.access.log  main;
    
        location / {
            rewrite ^/cat/([a-z]+)$ / break;
            proxy_pass http://localhost:8080/;
        } 
    
        ...
    }
    

    添加了 root /; 和新的 location 指令 .

    在正则表达式中忽略 ^$ 或省略 proxy_pass 地址的尾部反斜杠是一个失败的想法 .

    现在一切都按预期工作了 .

相关问题