【发布时间】:2019-11-01 06:07:20
【问题描述】:
我有一个在开发环境中运行良好的 ReactJS 应用程序。我正在使用 webpack。当我运行 yarn build 并将文件放到服务器上时,一切都运行良好。但是如果我在浏览器上单击刷新,我会得到 404。
我的服务器使用 Apache。我试过htaccess,我做过historyFallBackApi。他们似乎都没有解决我的问题
这是我的 .htaccess
RewriteBase /
RewriteCond %{REQUEST_URI} !^/(assets/?|$)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /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}`);
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),
);
这是我的路线
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;
这是我的自定义历史记录
import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
export default history;
我在服务器上的页面刷新时不断收到 404。
【问题讨论】:
-
我不了解 apache,但在已部署的应用程序上获得带有前端路由的 404 的经常性原因是您的服务器未配置为提供 SPA(例如,提供 html 文件和 bundle.js任何路线)
-
此代码
historyApiFallback: { index: '/' }正在发送入口点捆绑包,如果您可以像 Gael 提到的那样配置服务器,在每次请求时发送此捆绑包,则此问题将得到解决。这是 CSR 路由的棘手部分。 -
@GaëlS 如果我切换到 Nginx 还是一样
-
我需要有人带我走过@tunaayberk
-
您好@Temi'Topsy'Bello,您可以查看此帖子stackoverflow.com/a/16554242/11233593。我从未尝试过 apache,但这正是您所需要的。我会尝试 FallbackResource 重定向规则。如果这对您不起作用,请尝试 ember.js,就像他们在那篇文章中建议的那样。
标签: reactjs webpack react-router webpack-dev-server react-router-v4