簡體   English   中英

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

[英]React-Router 5 and Express - Catch-All Route Fallback

我正在使用 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...');
});

我將不勝感激任何幫助解決這個問題。

我假設您收到的錯誤是這樣的: 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"));
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM