React-Router V4-无法获取\* url \*

JavaScript React.js

西门番长

2020-03-19

我开始使用react-router v4。<Router>我的app.js中有一个简单的导航链接(请参见下面的代码)。如果我导航到localhost/vocabulary,路由器会将我重定向到正确的页面。但是,当我在之后按重新加载(F5)(localhost/vocabulary)时,所有内容消失并且浏览器报告Cannot GET /vocabulary那怎么可能?有人可以给我任何解决方法的提示(正确重新加载页面)吗?

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)

第2243篇《React-Router V4-无法获取\* url \*》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
老丝达蒙 2020.03.19

通过添加...我也成功了... historyApiFallback: true

devServer: {
    contentBase: path.join(__dirname, "public"),
    watchContentBase: true,
    publicPath: "/dist/",
    historyApiFallback: true
}
斯丁JimDavaid 2020.03.19

它对我有用devServer { historyApiFallback: true }只需要添加就可以,不需要使用publicPath: '/'

用法如下:

  devServer: {
    historyApiFallback: true
  },
小宇宙LEY 2020.03.19

只是为了补充泰勒对仍在为此挣扎的人的答案:

将其添加devServer.historyApiFallback: true到我的webpack配置中(不设置publicPath),修复了在刷新/返回/转发时看到的404 / Cannot-GET错误,但仅适用于单个级别的嵌套路由。换句话说,“ /”和“ / topics”开始正常工作,但是超出此范围的任何内容(例如“ / topics / whatever”)仍然在refresh / etc上抛出404。

刚刚在这里遇到了一个可以接受的答案:意外的令牌<反应路由器组件中的错误,它为我提供了最后丢失的部分。/在我的包脚本src中添加引导index.html已完全解决了该问题。

米亚伽罗L 2020.03.19

我遇到了同样的问题,为我解决的问题是编辑package.json文件,scripts: {

"build": "webpack -d && copy src\\index.html dist\\index.html /y && webpack-dev-server --content-base src --inline --port 3000"

在我的webpack build代码末尾,我添加了--history-api-fallback 这似乎也是解决该Cannot GET /url错误的最简单方法

注意:下一次在添加后进行构建时,--history-api-fallback您会注意到输出中的一行看起来像这样(无论您的索引文件是什么):

404将回退到/index.html

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android