webpack反应路由器无法导航子页面

时间:2016-02-17 17:37:29

标签: reactjs webpack react-router

我正在使用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'));

2 个答案:

答案 0 :(得分:0)

我知道你的意思。我也有这个问题,但是使用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

答案 1 :(得分:-1)

看起来您的服务器不准备处理路由器URL。您正在使用browserHistory,因此您需要configure your server返回所有路线网址的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;
  }
}