使用react-router和webpack响应改变的URL给页面找不到错误

我有以下webpackconfiguration文件:

var webpack = require('webpack'); var path = require('path'); var BUILD_DIR = path.resolve(__dirname, 'src/client/public'); var APP_DIR = path.resolve(__dirname, 'src/client/app'); var config = { entry: [ APP_DIR + '/config/routes.jsx', 'webpack/hot/dev-server', 'webpack-dev-server/client?http://localhost:8080' ], output: { publicPath: 'http://localhost:8080/src/client/public/' }, module : { loaders : [ { test: /\.jsx?$/, loader: 'babel-loader', include: APP_DIR, exclude: /node_modules/, query: { presets: ['es2015'] } }, { test: /\.scss$/, loaders: [ 'style', 'css', 'sass' ] }, { test: /\.json$/, loader: "json-loader" } ] } }; module.exports = config; 

所有我想要做的是在本地运行我的应用程序,但是当我点击:“ http:// localhost:8080 / src / client / home ”(根据我的routes.jsx和运行webpack-dev-server之后)

 import React from 'react'; import { Route, Router, browserHistory } from 'react-router'; import ReactDOM from 'react-dom'; import Wrapper from './../components/wrapper.jsx'; import Home from './../components/home.jsx'; import Projects from './../components/projects.jsx'; import SingleProject from './../components/projectContent/singleProject.jsx'; import About from './../components/aboutUs.jsx' ReactDOM.render(( <Router history={browserHistory} > <Route path="/" component={Wrapper} > <Route path="home" component={Home} /> <Route path="projects" component={Projects} /> <Route path="projects/:id" component={SingleProject} /> <Route path="about" component={About} /> </Route> </Router> ), document.getElementById('app')); 

我得到“无法GET / src / client / home”。

首先你已经在你的路线中提到家庭组件有path/home 。 所以你需要访问http://localhost:8080/home 。 此外,如果您尝试直接访问此url,它会给你这个错误,因为你使用browserHistory 。 如果你想在反应路由器v4中使用hashHistoryHashRouter ,在这种情况下,你将需要访问http://localhost:8080/#/home 。 如果您想继续使用browserHistoryBrowserRouter作为react-router v4,那么您需要在您的webpack中添加historyApiFallback historyApiFallback: true

 var webpack = require('webpack'); var path = require('path'); var BUILD_DIR = path.resolve(__dirname, 'src/client/public'); var APP_DIR = path.resolve(__dirname, 'src/client/app'); var config = { entry: [ APP_DIR + '/config/routes.jsx', 'webpack/hot/dev-server', 'webpack-dev-server/client?http://localhost:8080' ], output: { publicPath: 'http://localhost:8080/src/client/public/' }, devServer: { historyApiFallback: true }, module : { loaders : [ { test: /\.jsx?$/, loader: 'babel-loader', include: APP_DIR, exclude: /node_modules/, query: { presets: ['es2015'] } }, { test: /\.scss$/, loaders: [ 'style', 'css', 'sass' ] }, { test: /\.json$/, loader: "json-loader" } ] } }; module.exports = config; 

你需要添加这个在你的webpack设置:

 devServer: { historyApiFallback: true, }, 

并像这样启动你的服务器:

 webpack-dev-server --config webpack.config.js 

因为你需要React-Route来处理路由而不是你的服务器。 所以不pipe是什么url都应该去index.html。