React-router v4 - 无法获取* url * [英] React-router v4 - cannot GET *url*
问题描述
我开始使用react-router v4。我的app.js中有一个简单的< Router>
,带有一些导航链接(参见下面的代码)。如果我导航到 localhost / vocabulary
,路由器会将我重定向到正确的页面。但是,当我之后按下重新加载(F5)( localhost / vocabulary
)时,所有内容都会消失,浏览器报告无法获取/词汇
。怎么可能?有人能给我任何线索如何解决(正确重新加载页面)?
I started to use react-router v4. I have a simple <Router>
in my app.js with some navigation links (see code below). If I navigate to localhost/vocabulary
, router redirects me to the right page. However, when I press reload (F5) afterwards (localhost/vocabulary
), all content disappear and browser report Cannot GET /vocabulary
. How is that possible? Can somebody gives me any clue how to solve that (reload the page correctly)?
App.js:
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
import { Switch, Redirect } from 'react-router'
import Login from './pages/Login'
import Vocabulary from './pages/Vocabulary'
const appContainer = document.getElementById('app')
ReactDOM.render(
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/vocabulary">Vocabulary</Link></li>
</ul>
<Switch>
<Route exact path="/" component={Login} />
<Route exact path="/vocabulary" component={Vocabulary} />
</Switch>
</div>
</Router>,
appContainer)
推荐答案
我假设你正在使用Webpack。如果是这样,在webpack配置中添加一些内容应该可以解决问题。具体来说, output.publicPath ='/'
和 devServer.historyApiFallback = true
。下面是一个示例webpack配置,下面使用了^并修复了我的刷新问题。如果您对为什么感到好奇,请此会有所帮助。
I'm assuming you're using Webpack. If so, adding a few things to your webpack config should solve the issue. Specifically, output.publicPath = '/'
and devServer.historyApiFallback = true
. Here's an example webpack config below which uses both of ^ and fixes the refresh issue for me. If you're curious "why", this will help.
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './app/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
publicPath: '/'
},
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ]}
]
},
devServer: {
historyApiFallback: true,
},
plugins: [
new HtmlWebpackPlugin({
template: 'app/index.html'
})
]
};
我在这里写了更多关于此的内容 - 使用React Router修复无法GET / URL错误(或客户端路由器如何工作)
I wrote more about this here - Fixing the "cannot GET /URL" error on refresh with React Router (or how client side routers work)
这篇关于React-router v4 - 无法获取* url *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!