1. 首页
  2. >
  3. 前端开发
  4. >
  5. React

Ant Design Pro项目在browserHistory模式下刷新页面404问题解决方法

Ant Design Pro是基于react的项目,默认配置时,使用的是browserHistory模式,而不是hashHistory模式。browserHistory模式使用的是真实的url地址,调试的时候可能是正常的,如果部署到服务器上,就可能会出现页面404的异常,因为实际地址不存在。官方也有说明:


前端路由与服务端的结合#
如果你遇到 https://cdn.com/users/123 刷新后 404 的问题,你需要按照这个章节进行处理。

Ant Design Pro 使用的 Umi 支持两种路由方式:browserHistory 和 hashHistory。

可以在 config/config.js 中进行配置选择用哪个方式:

export default {
  history: 'hash', // 默认是 browser
};
hashHistory 使用如 https://cdn.com/#/users/123 这样的 URL,取井号后面的字符作为路径。browserHistory 则直接使用 https://cdn.com/users/123 这样的 URL。使用 hashHistory 时浏览器访问到的始终都是根目录下 index.html。使用 browserHistory 则需要服务器做好处理 URL 的准备,处理应用启动最初的 / 这样的请求应该没问题,但当用户来回跳转并在 /users/123 刷新时,服务器就会收到来自 /users/123 的请求,这时你需要配置服务器能处理这个 URL 返回正确的 index.html。强烈推荐使用默认的 browserHistory。

强烈推荐使用默认的 browserHistory.
官方也推荐使用browserHistory。因此下面我们来看看如何配置服务器。


1、Node配置:


const express = require('express')
const path = require('path')
const port = process.env.PORT || 8080
const app = express()
 
// 通常用于加载静态资源
app.use(express.static(__dirname + '/public'))
 
// 在你应用 JavaScript 文件中包含了一个 script 标签
// 的 index.html 中处理任何一个 route
app.get('*', function (request, response){
 response.sendFile(path.resolve(__dirname, 'public', 'index.html'))
})
 
app.listen(port)
console.log("server started on port " + port)
2、Apache配置



RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
3、Nginx配置



server {
 ...
 location / {
  try_files $uri /index.html
 }
}


4、IIS配置

<rewrite>
    <rules>
        <rule name="Imported Rule 1" stopProcessing="true">
            <match url="^index\.html$" ignoreCase="false" />
            <action type="None" />
        </rule>
        <rule name="Imported Rule 2" stopProcessing="true">
            <match url="." ignoreCase="false" />
            <conditions logicalGrouping="MatchAll">
                <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
            </conditions>
            <action type="Rewrite" url="/index.html" />
        </rule>
    </rules>
</rewrite>