React JS react-router-dom 导致 404

IT技术 reactjs react-router-dom
2021-05-22 15:57:18

我对 React 相当陌生,正在尝试利用 React 路由器功能。我在指向某个 URL 的电视屏幕上显示静态页面。

在我的开发环境中一切正常。当我输入正确的路径时,它指向设置的组件。将其加载到我的托管服务器上并在指向所需路径的 Live URL 上进行测试时,会产生 404。

import React, { Component } from 'react';
import './style/App.css';
import Header from './js/components/header';
import Menu from './js/components/menu';
import MenuTwo from './js/components/menuTwo';
import {  BrowserRouter as Router,  Route, Switch, Link } from 'react-
router-dom';

class App extends Component {
  render() {
   return (
     <Router>
  <div>
      <Header headerProp="maxwell's pizzeria" /> 
      <Route path="/" exact component={Menu} />
      <Route path="/menuTwo" exact component={MenuTwo} />

  </div>

  </Router>
  )
 }
}

export default App;

我也不太熟悉的webpack.config如下:

var webpack = require('webpack');
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'public');
var APP_DIR = path.resolve(__dirname, 'src/build');

// Existing Code ....
var config = {
 // Existing Code ....
 module : {
  loaders : [
   {
    test : /\.jsx?/,
    include : APP_DIR,
    loader : 'babel'
  }
  ]
 }
}

module.exports = config;
1个回答

首先检查您homepagepackage.json.

"homepage": "http://example.com/path/to/app",

那么您可以尝试一些重写规则来指向.htaccess文件中的应用程序

#Options All -Indexes
Options -Indexes
<Files *.php>
    ForceType application/x-httpd-php5
</Files>
# BEGIN My App Web-App
<ifModule mod_rewrite.c>
  Options +FollowSymLinks
  IndexIgnore */*
  RewriteEngine On
  RewriteBase /path/to/app/
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule (.*) /path/to/app/index.html
</ifModule>
# END   My App Web-App

编辑

当然basename,在Router

<Router basename='/path/to/app'>