React Router子路由未显示

时间:2018-07-31 02:37:00

标签: javascript reactjs routing react-router react-router-dom

我正在使用react-router-dom在我的应用程序内进行路由。我在显示子路线时遇到困难。我有2条路由,localhost:8080 /和localhost:8080 / posts / new。 localhost:8080 /路由按预期工作。如果我将第二条路由更改为/ posts,例如localhost:8080 / posts,那么它将毫无问题地显示。我正在'/'路线上使用确切的道具,并在webpack devServer中设置了以下配置:{historyApiFallback:true},但是这不能解决问题。

我在控制台中遇到2个错误:

错误#1: GET http://localhost:8080/posts/bundle.js 404 (未找到)。

错误2::拒绝执行“ http://localhost:8080/posts/bundle.js”中的脚本,因为它的MIME类型(“ text / html”)不可执行,并且是严格的MIME类型检查已启用。

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
import reduxPromise from 'redux-promise';

import reducers from './reducers/index';
import PostsIndex from './components/posts-index';
import PostsNew from './components/posts-new';

const createStoreWithMiddleware = applyMiddleware(reduxPromise)(createStore);

ReactDOM.render(
    <Provider store={createStoreWithMiddleware(reducers)}>
      <Router>
        <Switch>
            <Route exact path="/" component={PostsIndex} />
            <Route path="/posts/new" component={PostsNew} />
        </Switch>
      </Router>
   </Provider>, document.querySelector('.container'));

webpack.config.js

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename:'bundle.js'
    },
    module: {
        rules: [
            {
                exclude: /node_modules/,
                test: /\.js$/,
                use: 'babel-loader'
            }
        ]
    },
    plugins: [
        new HTMLWebpackPlugin({
            template: './src/index.html',
            filename: 'index.html'
        })
    ],
    devServer: {
        historyApiFallback: true
    }
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

HTMLWebpackPluginoutput.publicPath插入到HTML文件中注入的所有资产之前。如果没有publicPath,则JavaScript文件将作为<script src="bundle.js"></script>注入。因此,bundle.js将相对于您当前的URL加载,这不是您想要的。

publicPath设置为/,它应该可以正常工作。

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename:'bundle.js',
        publicPath: '/'
    },
    // ...
}