不能使用ReactJS、webpack、express来GET路径。

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

我几乎尝试了所有的解决方案,但我找不到任何解决这个问题的方法。我使用express来渲染我的ReactJS代码,用webpack构建。我可以毫无问题地打开页面,直到我被从主页重定向。但当我尝试在浏览器上输入URL或刷新页面时,我无法看到该页面。相反,我看到了这个错误。

Cannot GET /path

我也试过添加 historyApiFallback: true 对我 webpack.config.js 但没有成功。

以下是我的脚本,来自 package.json

{
  ...
  "scripts": {
    "build": "webpack --config webpack.config.js",
    "dev": "webpack-dev-server --mode development --open",
    "start": "npm run build && node server.js"
  },
  ...
}

而这是我的 webpack.config.js:

const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require('path');

const htmlPlugin = new HtmlWebPackPlugin({
    template: "./src/index.html",
    filename: "./index.html"
});

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'main.js',
        publicPath: '/',
    },
    devServer: {
        historyApiFallback: true,
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: "babel-loader"
            },
            {
                test: /\.css$/,
                use: ["style-loader", "css-loader"]
            },
        ]
    },
    plugins: [htmlPlugin],
    resolve: {
        extensions: ['*', '.js', '.jsx']
    },
};

还有 server.js 文件。

const path = require('path');
const express = require('express');
const PORT = process.env.PORT || 3000;

const app = express();
app.use(express.static(path.join(__dirname, 'dist')));

app.get('/', function(request, response) {
  response.sendFile(__dirname + '/dist/index.html');
});

app.listen(PORT, error => (
  error
    ? console.error(error)
    : console.info(`Listening on port ${PORT}. Visit http://localhost:${PORT}/ in your browser.`)
));

重要提示:

当我在服务器上运行 npm run dev,没有问题。我可以手动输入URL并刷新页面。

但当我在运行服务器时,用 npm run start,我正面临着我上面描述的问题。

node.js reactjs express webpack webpack-dev-server
1个回答
1
投票

app.get('/', ... ); 只发送回 index.html 在...上 / 路径,你需要在 每一 路径

app.get('*', function(request, response) {
  response.sendFile(__dirname + '/dist/index.html');
});
© www.soinside.com 2019 - 2024. All rights reserved.