0

I've tried almost every solution but I can't find any solution for this problem. I'm using express to render my ReactJS code, build with webpack. I can open pages without any issues until I'm being redirected from home page. But when I tried entering the URL on browser or refresh the page, I cannot see the page. Instead I see this error:

Cannot GET /path

I have also tried adding historyApiFallback: true to my webpack.config.js but no luck there.

Below are my scripts from package.json

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

And this is my 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']
    },
};

And the server.js file:

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.`)
));

Important NOTE

When I run server with npm run dev, there is no issues. I can enter URL manually and refresh the page.

But when I run server with npm run start, I am facing the issue I described above.

1 Answer 1

1

app.get('/', ... ); only sends back the index.html on the / path, you need to return it on every path

app.get('*', function(request, response) {
  response.sendFile(__dirname + '/dist/index.html');
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.