Somendra Meena
Somendra Meena

Reputation: 149

Cannot GET /path using ReactJS, webpack, express

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.

Upvotes: 0

Views: 693

Answers (1)

Martin
Martin

Reputation: 2273

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');
});

Upvotes: 1

Related Questions