【问题标题】:Routing issue in React with WebpackReact 与 Webpack 中的路由问题
【发布时间】:2017-05-17 23:14:07
【问题描述】:

我在我的应用中路由如下:

render(
  <Provider store={store}>
      <Router history={browserHistory }>
        <Route path={"/" component={TopContainer}>
            <IndexRoute component={Login} />
            <Route path='main' component={Maintainer} />    
        </Route>
    </Router>
  </Provider>,
  document.getElementById('root')
)

然后我将我的生产 bundle.js 和 index.html 直接部署在我的 web 根目录下(ubuntu 中的 apache)。 我可以通过http://...com/ 访问我的应用程序 问题是主页面加载完路由后

<Route path='main' component={Maintainer} />    

浏览器位置的内容变为:http://...com/main

此时,如果我用 url (http://...com/main) 重新加载页面,我会收到一个找不到页面的错误:“在此服务器上找不到请求的 URL /main。”

这里是我的 webpack.production.config.js

var webpack = require('webpack');
var path = require('path');
var loaders = require('./webpack.loaders');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var WebpackCleanupPlugin = require('webpack-cleanup-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

loaders.push({
  test: /\.scss$/,
  loader: ExtractTextPlugin.extract({fallback: 'style-loader', use : 'css-loader?sourceMap&localIdentName=[local]___[hash:base64:5]!sass-loader?outputStyle=expanded'}),
  exclude: ['node_modules']
});

module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    publicPath: './',       
    path: path.join(__dirname, 'public'),
    filename: '[chunkhash].js'
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  module: {
    loaders
  },
  plugins: [
    new WebpackCleanupPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        screw_ie8: true,
        drop_console: true,
        drop_debugger: true
      }
    }),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new ExtractTextPlugin({
      filename: 'style.css',
      allChunks: true
    }),
    new HtmlWebpackPlugin({
      template: './index.html',
      files: {
        css: ['style.css'],
        js: ['bundle.js'],
      }
    })
  ]
};

但是如果我在本地服务器上运行,就没有这样的问题了:

"use strict";
var webpack = require('webpack');
var path = require('path');
var loaders = require('./webpack.loaders');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var DashboardPlugin = require('webpack-dashboard/plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

const HOST = process.env.HOST || "127.0.0.1";
const PORT = process.env.PORT || "3000";

loaders.push({
  test: /\.scss$/,
  loaders: ['style-loader', 'css-loader?importLoaders=1', 'sass-loader'],
  exclude: ['node_modules']
});

module.exports = {
  entry: [
    'react-hot-loader/patch',
    './src/index.js', // your app's entry point
  ],
  devtool: process.env.WEBPACK_DEVTOOL || 'eval-source-map',
  output: {
    publicPath: '/',
    path: path.join(__dirname, 'public'),
    filename: 'bundle.js'
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  module: {
    loaders
  },
  devServer: {
    contentBase: "./public",
    // do not print bundle build stats
    noInfo: true,
    // enable HMR
    hot: true,
    // embed the webpack-dev-server runtime into the bundle
    inline: true,
    // serve index.html in place of 404 responses to allow HTML5 history
    historyApiFallback: true,
    port: PORT,
    host: HOST
  },
  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new ExtractTextPlugin({
      filename: 'style.css',
      allChunks: true
    }),
    new DashboardPlugin(),
    new HtmlWebpackPlugin({
      template: './index.html',
      files: {
        css: ['style.css'],
        js: [ "bundle.js"],
      }
    }),
  ]
};

我也在 node.js 网络服务器上尝试过,遇到了同样的问题。

contentBase: "./public" 成功了吗?

谢谢

酷分享

【问题讨论】:

  • 看起来你的 webpack/routing 配置是正确的。特别是如果你说它在开发中有效。我的猜测是您的服务器端需要将所有 url(可能除了 static/assets 文件夹?)路由到您的index.html,然后react-router 接管路由。
  • contentBase 正是 webpack 开发服务器从图像等中查找静态文件的地方 问题似乎是,虽然 webpack 开发服务器会在本地自动为您处理 url 映射,但您的生产服务器没有这种奢侈,你仍然需要让它知道如何以及在哪里使用 .htaccess/nginx.conf 等来提供文件,具体取决于你在 prod 中使用的服务器在表面下它使用 pushstate 而不是普通的 url 路由,所以你会需要您的服务器将所有 url 指向您的索引页面,JS 可以在其中提取并进行自己的路由
  • 抱歉,我似乎无法编辑我对 Firefox 的评论...这里有一个链接可以帮助您配置 apache 服务器以将所有内容(静态文件除外)重定向到您的 @ 987654333@ 以便 Javascript 可以管理自己的路由。 gkedge.gitbooks.io/react-router-in-the-real/content/apache.html
  • 感谢您的快速回复。我想要正确的内部路由。 “将所有 url(除了 static/assets 文件夹?)路由到您的 index.html ”不是我想要的。也就是说, http://...com/ 去我的登录页面,而 http://...com/main 应该去我的主页, http://...com/second 应该被路由到我的第二页...
  • 是的,马克...但我们说的是你有两个不同的路线。由 JS/React-router 完成的一个似乎适用于您的“本地案例”,另一个由 Apache 在服务器端完成。服务器端路由发生在客户端路由之前。这意味着当您转到 ...com/main 时,服务器路由器不知道此 URL 并引发 404 错误。如果您将此 URL 路由到 index.html,那么 JS 路由器将激活并显示正确的页面。

标签: reactjs webpack routes


【解决方案1】:

根据 Vincent 的建议,我在我的 Apache 配置中添加了一些重定向

    DocumentRoot /var/www

    Redirect permanent /main http://...com/

这项工作部分完成:Apache 确实将 http://...com/main 路由到 http://...com/

问题是,从那时起 React 接管了它,但它将它路由到登录屏幕而不是我预期的 - 重新加载浏览器页面时留在当前屏幕 http://...com/main

“如果您将此 URL 路由到您的 index.html,那么 JS 路由器将激活并显示正确的页面。”不是真的:我试过了

Redirect permanent /main http://...com/index.html

而 Apache 无法识别 http://...com/index.html

但是阿帕奇

似乎没有办法将其路由到主页...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-07
    • 2021-05-21
    • 2019-03-17
    • 2020-10-09
    • 2018-07-11
    • 2019-07-07
    • 1970-01-01
    • 2017-10-07
    相关资源
    最近更新 更多