欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

angular 前端路由不生效解决方案

程序员文章站 2022-10-08 22:46:44
最近使用 Angular 为我的活动室预约项目开发一个前后端分离的客户端,在部署上遇到了一个问题,前端路由不生效,这里记录一下。本地开发正常,但是部署到服务器上就有问题,之前部署到IIS上时需要配置一个 url rewrite ,可能遇到了类似的问题,查阅一番之后确实是这样。 ......

angular 前端路由不生效解决方案

intro

最近使用 angular 为我的活动室预约项目开发一个前后端分离的客户端,在部署上遇到了一个问题,前端路由不生效,这里记录一下。本地开发正常,但是部署到服务器上就有问题,之前部署到iis上时需要配置一个 url rewrite ,可能遇到了类似的问题,查阅一番之后确实是这样。

启用前端路由服务器配置

没有一种配置可以适用于所有服务器。 后面这些部分会描述对常见服务器的配置方式。 这个列表虽然不够详尽,但可以为你提供一个良好的起点。

  • apache:在 .htaccess 文件中添加一个, 代码如下():
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
try_files $uri $uri/ /index.html;
  • iis:往 web.config 中添加一条重写规则,类似于:
<system.webserver>
  <rewrite>
    <rules>
      <rule name="angular routes" stopprocessing="true">
        <match url=".*" />
        <conditions logicalgrouping="matchall">
          <add input="{request_filename}" matchtype="isfile" negate="true" />
          <add input="{request_filename}" matchtype="isdirectory" negate="true" />
        </conditions>
        <action type="rewrite" url="/index.html" />
      </rule>
    </rules>
  </rewrite>
</system.webserver>
  • github 页面服务:你没办法 github 的页面服务,但可以添加一个 404 页,只要把 index.html 复制到 404.html 就可以了。 它仍然会给出一个 404 响应,但是浏览器将会正确处理该页,并正常加载该应用。 使用 并也是一个好办法。

  • firebase 主机服务:添加一条。

"rewrites": [ {
  "source": "**",
  "destination": "/index.html"
} ]

docker 部署

我使用了 docker 部署,最后部署在 nginx 下了,按上面的提示在 nginx 配置中配置 try file,修改 nginx 默认配置文件如下:

server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

在打包 docker 镜像时替换默认的 nginx 配置,dockerfile 如下所示:

from node:12-alpine as builder
# set working directory
workdir /app

# install and cache app dependencies
copy package.json .
run npm install

# build the angular app
copy . .
run npm run build

from nginx:alpine

# copy from dist to nginx root dir
copy --from=builder /app/dist/reservationclient /usr/share/nginx/html

# expose port 80
expose 80

# set author info
label maintainer="weihanli"

copy ./conf/nginx.default.conf /etc/nginx/conf.d/default.conf

# run nginx in foreground
# https://*.com/questions/18861300/how-to-run-nginx-within-a-docker-container-without-halting
cmd ["nginx", "-g", "daemon off;"]

按上面的 dockerfile 打包之后前端路由就可以正常使用了~~

我的 angular 做的活动室预约客户端体验地址:

reference