React-router中使用BrowserRouter跳转后刷新出现404问题的解决

版权声明:转载或者引用请标明来源! https://blog.csdn.net/qq575792372/article/details/87193338

react路由的browserRouter使用的是h5 history API 的高阶路由组件,保证你的 UI 界面和 URL 保持同步。但是有个缺点,一刷新页面就会出现404找不到,原因是本地开发webpack是从内存中读取资源browserRouter从实际引入中并未找到文件。

解决方案一:

使用HashRouter来跳转,只是url里会带一个#号,不是太美观。

解决方案二:

修改webpack的配置文件,主要是配置historyApiFallback,这样跳转后在当前页面刷新就不会出现404了。

devServer: {
        clientLogLevel: 'warning',
        historyApiFallback: {
            rewrites: [
                { from: /.*/, to: path.posix.join(config.dev.assertPublicPath,'index.html') },
            ],
        },
        hot: true,
        contentBase: false, // since we use CopyWebpackPlugin.
        compress: true,
        open:true,
        port:config.dev.port,
    },
    plugins: [
        new CopyWebpackPlugin([
            {
                from: path.resolve(__dirname, '../static'),
                to: config.dev.assetsSubDirectory,
                ignore: ['.*']
            }
        ])
    ]

猜你喜欢

转载自blog.csdn.net/qq575792372/article/details/87193338