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

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

Intro

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

启用前端路由服务器配置

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

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>
"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://stackoverflow.com/questions/18861300/how-to-run-nginx-within-a-docker-container-without-halting
CMD ["nginx", "-g", "daemon off;"]

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

我的 angular 做的活动室预约客户端体验地址:https://reservation-preview.weihanli.xyz/

Reference

posted @ 2019-06-28 10:27 WeihanLi 阅读(...) 评论(...) 编辑 收藏