React Production Build 在页面刷新时显示 404 [英] React Production Build shows 404 on page refresh

查看:40
本文介绍了React Production Build 在页面刷新时显示 404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ReactJS 应用程序,它在开发环境中运行良好.我正在使用 webpack.当我运行 yarn build 并将我的文件放在我的服务器上时,一切都运行良好.但是如果我在浏览器上点击刷新,我会得到一个 404.

我的服务器使用 Apache.我试过htaccess,我做过historyFallBackApi.他们似乎都没有解决我的问题

这是我的 .htaccess

RewriteBase/RewriteCond %{REQUEST_URI} !^/(assets/?|$)RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-d重写规则./index.html [L]

这是我的 webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin');const modeConfig = env =>require(`./config/webpack.${env}`)(env);const webpackMerge = require('webpack-merge');const path = require('path');module.exports = ({ mode } = { mode: 'development', presets: [] },) =>//console.log(`mode: ${mode}`);网络包合并({模式,条目:'./src/index.js',解决: {扩展名:['.js', '.jsx', '.css', 'scss'],},开发服务器:{historyApiFallback: { index: '/' },contentBase: './',打开:真实,端口:4100,},模块: {规则: [{测试:/\.(png|jpg|jpeg|gif|ico)$/,排除:/node_modules/,loader: 'url-loader?limit=8192',},{测试:/\.(js|jsx|mjs)$/,排除:/node_modules/,使用:'babel-loader',},{测试:/\.(woff|woff2|eot|ttf)$/,loader: 'url-loader?limit=100000',},{测试:/\.svg$/,loader: 'svg-inline-loader?classPrefix',},],},输出: {公共路径:'/',路径:path.resolve(__dirname, 'build'),文件名:'bundle.js',},插件: [新的 HtmlWebpackPlugin({模板:'./public/index.html',}),//新的 FaviconsWebpackPlugin({ logo: "./public/image.png" })],},模式配置(模式),);

这是我的路线

<预><代码>功能应用(){返回 (<路由器历史={历史}><开关><路由精确路径="/" component={LoginComponent}/><Route path="/reset-password" component={ResetPassword}/><Route path="/dashboard" component={Dashboard}/><Route path="/cards" component={CardsList}/><Route path="/view-card" component={ViewCard}/><Route path="/transactions" component={Transfer}/><Route path="/users" component={UsersList}/><Route path="/edit-user" component={EditUser}/></开关></路由器>);}导出默认应用程序;

这是我的自定义历史

import { createBrowserHistory } from 'history';const 历史 = createBrowserHistory();导出默认历史记录;

我在服务器上刷新页面时不断收到 404.

解决方案

我会将您的 .htaccess 文件更新为这样.问题很可能是您当前用作 .htaccess 文件的内容没有将 404 错误重定向到 index.html:

RewriteEngine OnRewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d重写规则 ^ - [L]重写规则 ^/index.html [L]

我还会添加一个自定义 404 页面.为此,您需要创建一个新组件并向您的交换机添加另一条路由.路由不应该有路径,应该是交换机的最后一条路由.

I have a ReactJS application which works very well on development environment. I am using webpack. When I run yarn build and I drop my files on my server, everything runs fine. but if I click refresh on the browser, I get a 404.

My server uses Apache. I have tried htaccess, I have done historyFallBackApi. None of them seem to solve my problem

Here is my .htaccess

RewriteBase /
RewriteCond %{REQUEST_URI} !^/(assets/?|$)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]

Here is my webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin');

const modeConfig = env => require(`./config/webpack.${env}`)(env);
const webpackMerge = require('webpack-merge');
const path = require('path');


module.exports = (
    { mode } = { mode: 'development', presets: [] },
) =>
// console.log(`mode: ${mode}`);
    webpackMerge(
        {
            mode,
            entry: './src/index.js',
            resolve: {
                extensions: ['.js', '.jsx', '.css', 'scss'],
            },
            devServer: {
                historyApiFallback: { index: '/' },
                contentBase: './',
                open: true,
                port: 4100,
            },
            module: {
                rules: [
                    {
                        test: /\.(png|jpg|jpeg|gif|ico)$/,
                        exclude: /node_modules/,
                        loader: 'url-loader?limit=8192',
                    },
                    {
                        test: /\.(js|jsx|mjs)$/,
                        exclude: /node_modules/,
                        use: 'babel-loader',
                    },
                    {
                        test: /\.(woff|woff2|eot|ttf)$/,
                        loader: 'url-loader?limit=100000',
                    },
                    {
                        test: /\.svg$/,
                        loader: 'svg-inline-loader?classPrefix',
                    },
                ],
            },

            output: {
                publicPath: '/',
                path: path.resolve(__dirname, 'build'),
                filename: 'bundle.js',
            },
            plugins: [
                new HtmlWebpackPlugin({
                    template: './public/index.html',
                }),

                // new FaviconsWebpackPlugin({ logo: "./public/image.png" })
            ],
        },
        modeConfig(mode),
    );

Here is my route



function App() {
    return (
        <Router history={history}>
            <Switch>
                <Route exact path="/" component={LoginComponent} />
                <Route path="/reset-password" component={ResetPassword} />
                <Route path="/dashboard" component={Dashboard} />
                <Route path="/cards" component={CardsList} />
                <Route path="/view-card" component={ViewCard} />
                <Route path="/transactions" component={Transfer} />
                <Route path="/users" component={UsersList} />
                <Route path="/edit-user" component={EditUser} />
            </Switch>
        </Router>
    );
}

export default App;

Here is my custom history

import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

export default history;

I keep getting 404 on Page refresh on the server.

解决方案

I would update your .htaccess file to be like this. The problem is likely that what you are currently using as your .htaccess file does not redirect 404 errors to index.html:

RewriteEngine On  
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]

RewriteRule ^ /index.html [L]

I would also add a custom 404 page. To do that, you need to create a new component and add another route to your switch. The route shouldn't have a path and should be the last route of the switch.

<Route component={NotFoundComponent} />

这篇关于React Production Build 在页面刷新时显示 404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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