返回

IIS 服务器中的 Vue3 + Vite 路由问题诊断和解决指南

vue.js

IIS 服务器中的 Vue3 + Vite 路由故障排除指南

在使用 Vue3 和 Vite 构建的应用程序中,部署到 IIS 服务器时可能会遇到路由问题。在本文中,我们将探讨这些问题并提供详细的解决方案。

问题

当在 IIS 服务器上托管 Vue3 + Vite 应用程序时,会出现以下问题:

  • 通过 https://server_url/app_name/ 访问应用程序时,默认组件显示正常。
  • 但通过 https://server_url/app_name/index.html 访问时,<router-view> 中不会显示默认组件。

解决方法

解决此问题需要两个关键步骤:

1. 修改 App.vue 文件

在 App.vue 文件中,将 <router-view> 组件包裹在一个 <keep-alive> 组件中,如下所示:

<template>
  <div class="container-fluid fixed-main-container" style="padding: 0;">
    <navigation-bar></navigation-bar> 
    <keep-alive>
      <router-view></router-view>
    </keep-alive>
    <footer-bar></footer-bar>
  </div>
</template>

2. 修改 rewrite 规则

在 web.config 文件中,修改 rewrite 规则,添加以下行到 <conditions> 部分:

<add input="{IS_IIS7_URL_ENCODING}" pattern=".*" negate="true" />

修改后的 rewrite 规则如下:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Vue Router Routes" stopProcessing="true">
                    <match url=".*" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                        <add input="{IS_IIS7_URL_ENCODING}" pattern=".*" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.html" appendQueryString="false" logRewrittenUrl="true" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

原理

  • <keep-alive> 组件: 将路由组件缓存起来,避免在访问 index.html 时路由视图为空。
  • rewrite 规则: 解决 IIS 服务器在处理某些 URL 时遇到的问题。

其他注意事项

  • 确保应用程序已正确部署到 IIS 服务器。
  • 检查 IIS 服务器是否已启用 URL 重写模块。
  • 如果问题仍然存在,请尝试清除浏览器的缓存。

常见问题解答

1. 为什么需要在 App.vue 中使用 <keep-alive>

<keep-alive> 组件可以缓存路由组件,从而提高性能并解决在访问 index.html 时路由视图为空的问题。

2. 修改 rewrite 规则的目的是什么?

IIS 服务器在处理某些 URL 时可能会遇到问题,修改 rewrite 规则可以解决这些问题。

3. 我如何检查 IIS 服务器是否已启用 URL 重写模块?

打开 IIS 管理器,转到服务器节点,选择“URL 重写”。如果该模块已启用,它将显示在模块列表中。

4. 如果问题仍然存在,我该怎么办?

尝试清除浏览器的缓存,或查看 IIS 日志以获取有关错误的更多信息。

5. 如何避免此问题?

在开发时,可以使用 Node.js 服务器(例如 vite dev server)代替 IIS 服务器,因为 Node.js 服务器对 Vue 路由的处理更好。