react-router-dom路由问题,配置了historyApiFallback但是还是请求到后端了报404错误。
我在webpack中配置了historyApiFallback,但是地址访问类似/a/b已经定义的路由请求到后端了。请求类似/cc这种我定义的地址就会渲染定义的错误页面。
webpack.config.js
'use strict'
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const config = {
mode:'development',
entry: './src/app.js',
output: {
path: path.resolve(__dirname, 'dist')
},
devServer: {
port: '8088', //设置端口号
historyApiFallback: true
},
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options:{
presets : ['env', 'react']
}
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/template/index.html',
filename: 'index.html'
})
]
}
module.exports = config
app.js
import React from 'react'
import ReactDom from 'react-dom'
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom'
class A extends React.Component {
render() {
return (
<h1>
A
</h1>
)
}
}
class B extends React.Component {
render() {
return (
<h1>
B
</h1>
)
}
}
class C extends React.Component {
render() {
return (
<h1>
C
</h1>
)
}
}
class ErrorPage extends React.Component {
render() {
return (
<h1>
ErrorPage
</h1>
)
}
}
class App extends React.Component {
render() {
return (
<Router>
<Switch>
<Route exact path="/" component={A}/>
<Route path="/b" component={B}/>
<Route path="/c" component={C}/>
<Route path="/a/c" component={C}/>
<Route component={ErrorPage}/>
</Switch>
</Router>
)
}
}
ReactDom.render(
<App/>,
document.querySelector('#app')
)
访问http://localhost:8088/aa路由中未定义,会渲染ErrorPage
访问http://localhost:8088/a/c报如下错
GET http://localhost:8088/a/main.js 404 (Not Found)
Refused to execute script from 'http://localhost:8088/a/main.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
不知道哪里错了,各种搜索。看webpack的文档,然而并没解决掉问题。求大神指教!!!
不知道问题出在哪里了,我把所用的依赖版本信息也贴出来。
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.12.0",
"webpack-cli": "^3.0.3",
"webpack-dev-server": "^3.1.4"
},
"dependencies": {
"react": "^16.4.0",
"react-dom": "^16.4.0",
"react-router-dom": "^4.3.1"
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom'
改为:
import {HashRouter as Router, Route, Switch} from 'react-router-dom'
可以正常运行。
你如果不想访问到后端,应该使用HashRouter
试试这种方式,返回index.html