I am serving my front end code using node.js and express.js.
Here I'm facing an issue with my file path I provided in script src on different page URLs.
my project file structure is as follows:
react_jsx/
dst/
index.html
styles.css
main-62a2a28f9255e698905d.js // creating this file using a bundler.
Both styles.css and main-62a2a28f9255e698905d.js are adding to index.html dynamically using webpack bundler. But adding correctly as
<link href="style.css" rel="stylesheet"></head> and <script type="text/javascript" src="main-62a2a28f9255e698905d.js"></script>
Node server code is as follows:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.resolve(__dirname, 'react_jsx/dst')));
app.use(express.static(path.resolve(__dirname)));
// app.use('/react_jsx/dst',express.static(path.join(__dirname, '')));
app.use(express.static(path.join(__dirname, ' ')));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'react_jsx/dst/index.html'));
});
const PORT = process.env.PORT || 9000;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}!`);
});
The page is working fine on the base URL. ie., on localhost:9000.
But when I'm changing the page URL, the path to the files also changes. Suppose if the page Url is localhost:9000/app/login the path to my styles.css and main-[hash].js also changes.
The file path becoming localhost:9000/app/login/styles.css and localhost:9000/app/login/main-[hash].js
How can I resolve it? I went through a lot of SO answers and resolved issue with some other file paths, but couldn't resolve issue with files that located in the same folder of index.html