首页 文章

无法获取/手动输入的URL - React Router

提问于
浏览
0

我已经安装了React Router并使用了browserHistory,但是当我手动输入URL时,我得到 Cannot GET /:path .

任何想法为什么会这样?

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import {Router, browserHistory} from 'react-router';
import routes from './config/routes';

ReactDOM.render(<Router history={browserHistory} routes={routes} />, document.getElementById('app'));

routes.js

import React from 'react';
import {Route, IndexRoute} from 'react-router';

import App from '../components/app';
import Dashboard from '../components/dashboard';
import Expenditure from '../components/expenditure';
import Income from '../components/income';
import Transactions from '../components/transactions';

export default(
    <Route path='/' component={App}>
        <IndexRoute component={Dashboard} />
        <Route path='expenditure' component={Expenditure} />
        <Route path='income' component={Income} />
        <Route path='transactions' component={Transactions} />
    </Route>
);

单击导航将使用正确的路线完美显示内容 .

我正在使用webpack与webpack-dev-server一起编译 .

谢谢 :)

2 回答

  • 0

    您必须将所有非文件请求重定向到index.html,这是browserHistory工作所必需的 .

    在webpack-dev-server中有一个选项 historyApiFallback ,您必须将其设置为 true 才能实现 .

    有关更多信息,请参见webpack documentation

    new WebpackDevServer(compiler, {
        historyApiFallback: true
    
        // ...
    })
    
  • 0

    我今天遇到了同样的问题,无法在stackoverflow中找到答案 . 让 webpack.config.jsoutput.publicPath 中的路径等于 devServer.historyApiFallback.indexpoint out html file route .my webpack-dev-server 版本是1.10.1并且运行良好 . http://webpack.github.io/docs/webpack-dev-server.html#the-historyapifallback-option不起作用,你必须指出html文件路由 .

    例如:

    module.exports = {
        entry: "./src/app/index.js",
        output: {
            path: path.resolve(__dirname, 'build'),
            publicPath: 'build',
            filename: 'bundle-main.js'
        },
        devServer: {
            historyApiFallback:{
                index:'build/index.html'
            },
        },
        //其他的配置省略
    };
    

    historyApiFallback.index 表示当url路径与真实文件不匹配时, webpack-dev-server 使用 historyApiFallback.index 中的文件配置在浏览器而不是404页面中显示 . 然后关于你的路线改变的所有事情让你的js使用 react-router 做 .

相关问题