React-router v4 - GET *url* できません。

react-router v4を使い始めたのですが、app.jsにシンプルな<Router>といくつかのナビゲーションリンク(以下のコードを参照)を用意しています。もし私が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)
ソリューション

Webpackを使用しているのでしょうか?もしそうなら、webpack の設定にいくつかのことを追加することで問題が解決するはずです。具体的には、output.publicPath = '/'devServer.historyApiFallback = true を追加します。以下の webpack の設定例では ^ の両方が使用されており、私の場合は更新の問題が解決されました。なぜか気になる方は、this をご覧ください。

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で更新時の "cannot GET" エラーを修正する(またはクライアント側ルータの仕組み)

解説 (10)

まだ悩んでいる人のために、Tyler'さんの回答を補足しておきます。

webpack の設定に devServer.historyApiFallback: true を追加すると(publicPath を設定せずに)、更新/戻る/進むで見ていた 404/Cannot-GET エラーは直りましたが、1 レベルのネストしたルートに対してのみでした。 言い換えれば、"/" と "/topics" は正常に動作し始めましたが、それ以上 (例えば "/topics/whatever") はまだ更新時に 404 をスローしていました。

https://stackoverflow.com/questions/29718481/unexpected-token-error-in-react-router-component そしてそれは、私のために最後の欠けている部分を提供してくれました。 私の index.html のバンドルスクリプトの src に先頭の / を追加することで、問題は完全に解決されました。

解説 (0)

私も同じ問題を抱えていました。私の場合は、package.jsonファイルを編集して、scripts' の下で修正しました。{

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

の下に、 --history-api-fallback を追加しました。 これは Cannot GET /url エラーの最も簡単な解決方法のように思えました。

注意: --history-api-fallback を追加した後にビルドすると、次のような行が出力されます (インデックスファイルが何であれ)。

404は/index.htmlにフォールバックされます。

解説 (0)