React-Router 5和Express-捕获所有路由回退

问题描述 投票:0回答:1

我正在使用Redux,react-router和Webpack 4进行基于MERN堆栈的项目,对于我一生,我无法弄清楚自己在做什么错。我的开发版本工作正常,但是当我运行生产版本时,我的全部后备路线都行不通。 index.html文件仅在我使用express.static时才起作用,当我删除它时根本不起作用。当我导航到localhost:3000时,react路由器工作正常,但如果尝试手动导航到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个回答
0
投票

我假设您收到的错误是这样的:TypeError:路径必须是绝对路径,或将根目录指定为res.sendFile

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

app.get("*", (req, res) => {
  res.sendFile(path.resolve("./dist", "index.html"));
});
© www.soinside.com 2019 - 2024. All rights reserved.