【问题标题】:webpack react router unable to navigate child pageswebpack反应路由器无法导航子页面
【发布时间】:2016-05-29 13:50:54
【问题描述】:

我正在使用react-router 2.0webpack。我的 app.js 中有以下代码。当我导航到http://localhost:3000/ 时,我得到Main 页面。但是,如果我导航到http://localhost:3000/about,我希望about 页面可以全屏显示。但我收到一条错误消息Cannot GET /about。我应该在 webpack 配置上做些什么来允许这些路由吗?

import { Router, Route, Link, browserHistory } from 'react-router';
ReactDOM.render((
    <Router history={browserHistory}>
       <Route path="/" component={Main}>
         <Route path="about" component={About} />
         <Route path="help" component={Help} />
       </Route>          
    </Router>
), document.getElementById('app'));

【问题讨论】:

  • 您上面的代码似乎是正确的。也几乎与documentation 相同。
  • 是的,不确定服务器端出了什么问题,无法锻炼如何允许这些路由。
  • 你是如何实现你的路由器的?你在某处有Router.run 吗?
  • 我需要Router.run吗,根据他们的主页,我认为这就是所有需要的。
  • stackoverflow.com/questions/32682854/…,1.x 之前的路由方式。

标签: reactjs webpack react-router


【解决方案1】:

您的服务器似乎还没有准备好处理路由器 URL。您正在使用 browserHistory,因此您需要 configure your server 为您的所有路由 URL 返回您的 index.html

来自文档:

快递应用可能如下所示:

const express = require('express')
const path = require('path')
const port = process.env.PORT || 8080
const app = express()

// serve static assets normally
app.use(express.static(__dirname + '/public'))

// handle every other route with index.html, which will contain
// a script tag to your application's JavaScript file(s).
app.get('*', function (request, response){
  response.sendFile(path.resolve(__dirname, 'public', 'index.html'))
})

app.listen(port)
console.log("server started on port " + port)

如果您使用的是 nginx,请使用 try_files 指令:

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

【讨论】:

  • 没有阅读作者的要求,您只是从另一篇博文中复制并粘贴了一个解决方案。
【解决方案2】:

我知道你的意思。我也遇到了这个问题,但通过使用 browsersync 和 connect-history-api-fallback 解决了它。

创建一个名为 srcServer.js 的文件并添加类似这样的内容(当然要安装所需的所有依赖项):

// Require Browsersync along with webpack and middleware for it
import browserSync from 'browser-sync';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import historyApiFallback from 'connect-history-api-fallback';

const webpackConfig = {
    debug: true,
    devtool: 'cheap-module-eval-source-map',
    noInfo: true, 
    entry: './src/index',
    target:  'web', 
    output: {
        path: __dirname + '/dist', 
        publicPath: '',
        filename: 'bundle.js'
    },
    plugins: [], //[your array of plugins],
    module: {
        loaders: [] //[your array of loaders],
    }
}
const bundler = webpack(webpackConfig);

// Run Browsersync and use middleware for Hot Module Replacement
browserSync({
    server: {
        baseDir: 'src',

        middleware: [
            historyApiFallback(),  // <-- the key to loading a route in the url directly (without navigating to it first)
            webpackDevMiddleware(bundler, {
                // Dev middleware can't access config, so we provide publicPath
                publicPath: webpackConfig.output.publicPath,
                stats: {colors: true},
                noInfo: true
            }),
            // bundler should be the same as above
            webpackHotMiddleware(bundler)
        ]
    },

    // no need to watch '*.js' here, webpack will take care of it for us,
    // including full page reloads if HMR won't work
    files: [
        'src/*.html'
    ]
});

然后你可以在你的 package.json 中添加一个 npm 脚本,比如说npm run start:

  "scripts": {
     "start": "babel-node srcServer.js",
  },

这应该为您的文件提供connect-history-api-fallback,这将允许您直接加载和重新加载http://localhost:3000/about

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-28
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多