React 和 IIS 重写 url 配置

React and IIS rewrite url configuration

我对“React 路由”和“IIS 配置”有疑问。 我在 IIS 中添加了以下 url 重写角色:

<?xml version="1.0" encoding="UTF-8"?>    
<configuration>    
 <system.webServer>    
   <rewrite>    
     <rules>    
       <rule name="React 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>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*" />
            </customHeaders>
        </httpProtocol>    
 </system.webServer>    
</configuration> 

使用该配置,当我使用该应用程序进行导航时,它工作正常,但如果我尝试刷新页面,它就会变成空白,似乎 url 重写不起作用。 (如果我尝试使用节点服务器就不会发生这种情况)

看起来你的url重写规则配置是正确的,我认为问题应该是React路由没有处理url,如果索引页面没有发送请求到react 路由,这会导致问题。

这种情况,您可以尝试添加到Index.html页面,应该可以解决您的问题。并且 href 属性应该根据你的反应应用程序进行调整。

你也可以参考这个类似的案例:How do I setup react-router clean URL's with IIS?

感谢@Xudong Peng 的建议,帮助我解决了问题

问题出在脚本标签的路径上, 文件的 url 设置为相对路径而不是绝对路径:

<script defer="defer" src="main.bundle.js">

而不是:

<script defer="defer" src="/main.bundle.js">

这是由于缺少 webpack 配置造成的, 我没有在 output 节点

中设置 publicPath
output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist'),
        publicPath: '/',
        clean: true,
    }

补充一下问题就解决了