首页 > 解决方案 > ReactJS React-router-dom 不显示页面 | 无法获取 /{location}

问题描述

在 ReactJS 中,我有一个项目,在我现在得到错误之前,一切正常,我不记得我做错了什么。在我的开发本地主机上,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);
}

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

标签: javascriptreactjsreact-routerreact-router-dom

解决方案


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

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

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

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'));
    });
}

推荐阅读