【发布时间】: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