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

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

Intro

最近使用 Angular 為我的活動室預(yù)約項目開發(fā)一個前后端分離的客戶端,在部署上遇到了一個問題,前端路由不生效,這里記錄一下。本地開發(fā)正常,但是部署到服務(wù)器上就有問題,之前部署到IIS上時需要配置一個 url rewrite ,可能遇到了類似的問題,查閱一番之后確實是這樣。

啟用前端路由服務(wù)器配置

沒有一種配置可以適用于所有服務(wù)器。 后面這些部分會描述對常見服務(wù)器的配置方式。 這個列表雖然不夠詳盡,但可以為你提供一個良好的起點。

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 中添加一條重寫規(guī)則,類似于這里
<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 默認(rèn)配置文件如下:

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 鏡像時替換默認(rèn)的 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 做的活動室預(yù)約客戶端體驗地址:https://reservation-preview.weihanli.xyz/

Reference

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容