【问题标题】:ReactJS React-router-dom not showing the pages | Cannot GET /{location}ReactJS React-router-dom 不显示页面 |无法获取 /{location}
【发布时间】:2026-02-16 09:10:02
【问题描述】:

在 ReactJS 中,我有一个项目,在我现在遇到错误之前,一切正常,我不记得我做错了什么。在我的 dev localhost 上,URL 可以正常工作,但是当我在服务器上发布并运行 prod 时,只有索引页面可以工作,其他人甚至没有默认的 404 错误页面。

这是我使用的依赖项:

"dependencies": {
    "history": "^5.0.0",
    "local-storage-fallback": "^4.1.1",
    "react": "^16.4.1",
    "react-dom": "^16.4.1",
    "react-helmet": "^6.1.0",
    "react-meta-tags": "^1.0.1",
    "react-router-dom": "^4.3.1",
    "react-scripts": "1.1.4",
    "styled-components": "^5.2.1",
    "styled-theming": "^2.2.0"
  }

这也是我用来设置路由的 ViewPort:

import React, {Component} from 'react';

import {
  BrowserRouter as Router,
  Route,
  Switch,
  Redirect
} from 'react-router-dom';


import Home from './pages/Home.js';
import Regulations from './pages/Regulations.js';
import We from './pages/We.js';
import Error from './pages/Error.js';
import List from './pages/List.js';

import Article01 from './stories/Article01.js';


class ViewPort extends Component {
  render() {
    return <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/regulations" component={Regulations} />
        <Route path="/we" component={We} />

        <Route path="/feed" component={List} />
        <Route path="/stories/article01" component={Article01} />

        <Route path="/404" component={Error} />
        <Redirect to="/404" />

      </Switch>
    </Router>
  }
}

export default ViewPort;

这里是 Webpack.config.js:

'use strict';

const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
  module: {
    rules: [
      {
        test: /\.pug$/,
        use: [
          'pug-loader?self'
        ]
      },
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      },
    ]
  },
  plugins: [
    new UglifyJSPlugin()
  ]
};

ExpressWebServer 代码:

const express = require("express");
const bodyParser = require("body-parser");
const Papa = require("papaparse");
const fs = require("fs");
const path = require("path");
const http = require('http');
const https = require('https');
const app = express();

app.use(express.static(path.join(__dirname, "client/build")));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.get("/api", (req, res) => {
    const data = [
        {
            hide: "I remove the data for safety",
        },
    ];
    res.json(data);
    console.log("Data successfully was sent.");
});

if (process.env.NODE_ENV === "production") {
    app.use(express.static(path.join(__dirname, '../client/build')));
    app.get('/', function (req, res) {
        res.sendFile(path.join(__dirname, 'build', 'index.html'));
    });
}

if (process.env.NODE_ENV === "production") {
    const privateKey = fs.readFileSync('/etc/letsencrypt/live/mysite.com/privkey.pem', 'utf8');
    const certificate = fs.readFileSync('/etc/letsencrypt/live/mysite.com/cert.pem', 'utf8');
    const ca = fs.readFileSync('/etc/letsencrypt/live/mysite.com/chain.pem', 'utf8');
    const credentials = {
        key: privateKey,
        cert: certificate,
        ca: ca
    };

    https.createServer(credentials, app).listen(443, () => {
        console.log('Server is running on port 443');
    });
    http.createServer(function (req, res) {
        res.writeHead(301, {"Location": "https://" + req.headers['host'] + req.url});
        res.end();
    }).listen(80);
} else if (process.env.NODE_ENV === "development") {
    app.listen(9000);
} else {
    app.listen(9000);
}

如果可以在我发布时检查为什么这不起作用,但只能在我的本地主机上,这对某人来说会很好。

【问题讨论】:

  • 你使用什么网络服务器?
  • @Florin 我正在使用 Express,将其托管在 Ubuntu 20.4 上。
  • @SethLutske 我在哪里可以找到“devServer { historyApiFallback: true }”?
  • 你能分享你为页面提供服务的快速服务器代码

标签: javascript reactjs react-router react-router-dom


【解决方案1】:

你得到 404 的原因是因为当你在一个嵌套路由上时,你请求服务器为你提供你的文件,但它只向你发送 index.html /,因此对于其他路径它给你 404,因为你还没有配置响应。

这里的解决方案是为index.html 提供服务,而不管您的客户端路径如何,这样路由就可以在客户端进行。对于 webpack-dev-server,我们将 historyApiFallback 设置为 true,对于快速服务器,您需要在 app.get('*', 上发送 index.html

您可以使用以下代码进行更改

if (process.env.NODE_ENV === "production") {
    app.use(express.static(path.join(__dirname, '../client/build')));
    app.get('*', function (req, res) {
        res.sendFile(path.join(__dirname, 'build', 'index.html'));
    });
}

【讨论】:

  • 你能详细解释一下historyApiFallback,我该如何解决?
  • 你不需要historyApiFallback,你需要的是使用app.get('*', function (req, res) {请参考[this(]webpack.js.org/configuration/dev-server/…)了解historyApiFallback的更多信息
  • 我想我试过了,但没有奏效。舒巴姆。