如何使用 IIS 设置 react-router 干净的 URL? [英] How do I setup react-router clean URL's with IIS?

查看:49
本文介绍了如何使用 IIS 设置 react-router 干净的 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

React-Router 让您的 ReactJS 应用程序通过简单的路由组件成为 SPA.部署到 IIS 时,使用 bashHistory 进行设置时一切正常.但是,当我尝试使用 browserHistory 时,IIS 试图返回一个目录,而不是允许 React-Router 抓取和解析路由.我如何设置 React-Router 以在 IIS 环境中工作?

React-Router enables your ReactJS app to become a SPA through simple routing components. When deploying to IIS, everything works fine when setup using bashHistory. However, when I try to use browserHistory, IIS is trying to return a directory instead of allowing React-Router to grab and resolve the route. How do I setup React-Router to work in an IIS environment?

推荐答案

让 React-Router 与 IIS 一起工作的关键是设置 URL 重写规则.在查看其他人如何使用 IIS 设置 AngularJS SPA 应用程序后,我提出了以下解决方案.

The key to getting React-Router to work with IIS is to setup URL Rewrite rules. After looking at how some others have setup AngularJS SPA apps with IIS, I have come up with the following solution.

  1. 在您的服务器上下载并安装 URL Rewrite(开发和生产)

设置规则以捕获任何非文件和非目录的 url 路由.或者,您可以否定要定期提供的任何实际目录.可以在 Microsoft 文档中找到更多信息

Setup rule to catch any url routes that ARE NOT files and ARE NOT directories. Optionally, you can negate any actual directories that you want serve regularly. More info can be found here on Microsoft's Documentation

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
      <system.webServer>
      <rewrite>
        <rules>
          <rule name="ReactRouter Routes" stopProcessing="true">
            <match url=".*" />
            <conditions logicalGrouping="MatchAll">
              <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
              <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
              <add input="{REQUEST_URI}" pattern="^/(docs)" negate="true" />
            </conditions>
            <action type="Rewrite" url="index.html" />
          </rule>
        </rules>
      </rewrite>
    </system.webServer>
    </configuration>

  1. 在您的基本 html 页面 (index.html) 中,向您的应用添加带有 href 属性的 <base/> 标记.
  1. In your base html page (index.html) add a <base/> tag with a href attribute to your app.

这篇关于如何使用 IIS 设置 react-router 干净的 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆