【问题标题】:React Router Subroutes not showing反应路由器子路由未显示
【发布时间】:2019-01-07 08:05:42
【问题描述】:

我正在使用 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 类型检查。

索引.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
    }
}

感谢任何帮助。

【问题讨论】:

  • 如何在 HTML 文件中加载 bundle.js?确保它是/bundle.js 而不仅仅是bundle.js
  • 我正在使用 webpack-dev-server,所以我假设它默认执行此操作。但是,我在控制台中检查了脚本元素,它显示为简单的 bundle.js

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


【解决方案1】:

HTMLWebpackPluginoutput.publicPath 添加到它注入到 HTML 文件中的所有资产中。如果没有publicPath,JavaScript 文件将被注入为&lt;script src="bundle.js"&gt;&lt;/script&gt;。因此,bundle.js 将相对于您当前的 url 加载,这不是您想要的。

publicPath 设置为/,它应该可以按预期工作。

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

【讨论】:

    猜你喜欢
    • 2019-10-24
    • 1970-01-01
    • 2020-11-24
    • 2016-11-28
    • 1970-01-01
    • 2020-01-21
    • 2019-01-12
    • 2021-11-06
    • 2018-03-22
    相关资源
    最近更新 更多