N
N
Nikita2021-04-08 15:17:18
Node.js
Nikita, 2021-04-08 15:17:18

React application on node.js does not load when requested from a non-root url, how to fix it?

By a non-root url, I mean any url other than "/" ( localhost:3000 )
I want to ensure that for any url, node.js still gives index.html, and the url itself is processed by the react-router-dom client router.

const express = require('express');
const path = require('path');
const app = express();

app.use(express.static('./dist'));

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

app.use("*", (req, res) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept');
});

app.get('/*', function (req, res) {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

app.listen(3000, () => {
 console.log('SERVER STARTED ON PORT', 3000);
});

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question