React-Router 5 和 Express - Catch-All 路由回退

React-Router 5 and Express - Catch-All Route Fallback

我正在使用 Redux、react-router 和 Webpack 4 开发一个基于 MERN 堆栈的项目,我终其一生都不知道自己做错了什么。我的开发构建工作正常,但是当我 运行 我的生产构建时,我的 catch-all 回退路线不起作用。 index.html 文件之所以有效,是因为我正在使用 express.static,当我删除它时,它根本不起作用。当我导航到 localhost:3000 时,反应路由器工作正常,但如果我尝试手动导航到 localhost:3000/about,则会出现内部服务器错误。所以我假设 app.get 请求由于某种原因根本不起作用。这是我的服务器代码:

import express from 'express';
import path from 'path';

import bodyParser from 'body-parser';
import cors from 'cors';
import mongoose from 'mongoose';

const PORT = process.env.PORT;
const MONGODB_URI = process.env.MONGODB_URI;
const history = require('connect-history-api-fallback');

const app = express();

app.use(cors())

//DB setup
mongoose.Promise = global.Promise;
mongoose.connect(MONGODB_URI);
var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    console.log('We have been connected!');
});


if (process.env.NODE_ENV !== "production") {
    app.use(history());
    const webpack = require('webpack');
    const webpackDevMiddleware = require('webpack-dev-middleware');
    //require webpack config
    const config = require('../../webpack.dev.config.js');
    //create compiler
    const compiler = webpack(config);
    //use webpack-dev-middleware to serve the bundles
    app.use(webpackDevMiddleware(compiler, {
        publicPath: config.output.publicPath
    }));
    //enable HMR
    app.use(require('webpack-hot-middleware')(compiler));
} else {
    app.use(express.static("dist"));

    app.get("*", (req, res) => {
      res.sendFile(path.join("./dist", "index.html"));
    });
}



//Listen
app.listen(PORT, function() {
    console.log('Server is listening...');
});

如果能帮我解决这个问题,我将不胜感激。

我假设您收到的错误是这样的:TypeError: path must be absolute or specify root to res.sendFile

要解决此问题,您应该使用 path.resolve 而不是 path.join 并相应地调整路径:

app.get("*", (req, res) => {
  res.sendFile(path.resolve("./dist", "index.html"));
});