【问题标题】:React-Router 5 and Express - Catch-All Route FallbackReact-Router 5 和 Express - 包罗万象的路由后备
【发布时间】:2020-01-17 21:39:06
【问题描述】:

我正在使用 Redux、react-router 和 Webpack 4 开发一个基于 MERN 堆栈的项目,而在我的一生中,我无法弄清楚自己做错了什么。我的开发构建工作正常,但是当我运行生产构建时,我的包罗万象的后备路线不起作用。 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...');
});

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

【问题讨论】:

    标签: node.js reactjs express routing react-router


    【解决方案1】:

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

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

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

    【讨论】:

    • 我得到的唯一错误是内部服务器错误 500。我最初使用的是 path.resolve,但问题是一样的。
    • 您有关于 500 错误的任何其他信息吗?不幸的是,我不知道还有什么可以帮助的,因为 500 错误可能是很多事情。我只是假设了上述错误,因为我将您的代码复制到了示例项目中,这就是我得到的。
    • 哦,实际上,您的答案对我有用!在摆弄它时,我犯了一个错误,打破了它,这是路径的问题。非常感谢,非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2016-08-20
    • 2011-04-02
    • 1970-01-01
    • 2011-10-13
    • 2021-04-25
    • 2021-09-09
    • 1970-01-01
    • 2021-08-17
    相关资源
    最近更新 更多