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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM