Javascript React-router v4 - 无法获取 *url*
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43209666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React-router v4 - cannot GET *url*
提问by exoslav
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)?
我开始使用 react-router v4。<Router>我的 app.js 中有一个简单的导航链接(见下面的代码)。如果我导航到localhost/vocabulary,路由器会将我重定向到正确的页面。但是,当我之后按重新加载 (F5) ( localhost/vocabulary) 时,所有内容都会消失并且浏览器报告Cannot GET /vocabulary。这怎么可能?有人能给我任何解决方法的线索吗(正确重新加载页面)?
App.js:
应用程序.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)
回答by Tyler McGinnis
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", thiswill help.
我假设您正在使用 Webpack。如果是这样,在您的 webpack 配置中添加一些内容应该可以解决问题。具体来说,output.publicPath = '/'和devServer.historyApiFallback = true。这是下面的示例 webpack 配置,它同时使用 ^ 并为我修复了刷新问题。如果你好奇“为什么”,这会有所帮助。
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'
})
]
};
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 刷新时修复“无法获取 /URL”错误(或客户端路由器如何工作)
回答by Will Ashe
Just to supplement Tyler's answer for anyone still struggling with this:
只是为了补充泰勒对仍在为此苦苦挣扎的人的回答:
Adding the devServer.historyApiFallback: trueto my webpack config (without setting publicPath) fixed the 404/Cannot-GET errors I was seeing on refresh/back/forward, but only for a single level of nested route. In other words, "/" and "/topics" started working fine but anything beyond that (e.g. "/topics/whatever") still threw a 404 on refresh/etc.
添加devServer.historyApiFallback: true到我的 webpack 配置(没有设置publicPath)修复了我在刷新/返回/转发时看到的 404/Cannot-GET 错误,但仅适用于单个级别的嵌套路由。换句话说,“/”和“/topics”开始工作正常,但除此之外的任何内容(例如“/topics/whatever”)仍然在刷新/等时抛出404。
Just came across the accepted answer here: Unexpected token < error in react router componentand it provided the last missing piece for me. Adding the leading /to the bundle script src in my index.htmlhas solved the issue completely.
刚刚在这里遇到了接受的答案:意外令牌<反应路由器组件中的错误,它为我提供了最后一个缺失的部分。/在我的包脚本 src 中添加引导index.html已经完全解决了这个问题。
回答by kiss_von
It worked for me just need just addding devServer { historyApiFallback: true }is OK, not need use publicPath: '/'
它对我有用devServer { historyApiFallback: true },只需要添加就可以了,不需要使用publicPath: '/'
usage like:
用法如:
devServer: {
historyApiFallback: true
},
回答by jsina
If your application is hosted on a static file server, you need to use a instead of a .
如果您的应用程序托管在静态文件服务器上,则需要使用 .
import { HashRouter } from 'react-router-dom'
ReactDOM.render((
<HashRouter>
<App />
</HashRouter>
), holder)
回答by Jared
I was having the same issue, what fixed it for me was editing my package.jsonfile, and under scripts: {
我遇到了同样的问题,为我修复的是编辑我的package.json文件,然后在scripts: {
"build": "webpack -d && copy src\index.html dist\index.html /y && webpack-dev-server --content-base src --inline --port 3000"
at the end of my webpack buildcode I added --history-api-fallbackthis also seemed like the easiest solution to the Cannot GET /urlerror
在我的 webpackbuild代码的末尾,我添加了--history-api-fallback这似乎也是最简单的Cannot GET /url错误解决方案
Note: the next time you build after adding --history-api-fallbackyou will notice a line in the output that looks like this (with whatever your index file is):
注意:下次在添加后构建时,--history-api-fallback您会注意到输出中的一行看起来像这样(无论您的索引文件是什么):
404s will fallback to /index.html
404s 将回退到 /index.html
回答by Alex
If you use Webpack check your configuration in part of server configuration for the "contentBase" attribute. You can set by this example:
如果您使用 Webpack,请在服务器配置的一部分中检查“contentBase”属性的配置。你可以通过这个例子设置:
devServer: {
...
contentBase: path.join(__dirname, '../')
...
}
回答by SheldonO'Reilly
I also had success with this by adding ... historyApiFallback: true
我也通过添加... historyApiFallback: true
devServer: {
contentBase: path.join(__dirname, "public"),
watchContentBase: true,
publicPath: "/dist/",
historyApiFallback: true
}
回答by Marty McGee
If you are using Express (not Webpack), this worked for me..
如果您使用的是 Express(不是 Webpack),这对我有用..
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, 'path/to/your/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})

