Node - CSS File not being picked on one path but picked on other

Viewed 31

I have a html file, being generated by a third party library that I need to serve on a route in a node server.

The html file and the related css files are generated in a folder called public having the following structure.

src -|
     | - public -|
     |           | - css -|
     |           |        | - css-file.css
     |           | - index.html
     | - server.js

The html file refers to the css file as

<link rel="stylesheet" href="css/css-file.css" />

I cannot change this, as the index.html and the related css file is being generated by a third party library.

In the server.js file, I have the following code

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

app.get('/path/one',(req, res) => {
   res.set({'Content-Type': 'text/html'});
   res.sendFile(path.join(__dirname, './public/index.html'))
}

app.get('/pathTwo', (req, res) => {
   res.set({'Content-Type': 'text/html'});
   res.sendFile(path.join(__dirname, './public/index.html'))   
}

The css file gets picked up on /pathTwo, but does not get picked up on /path/one. I am not able to figure out why.

Edit One thing that I notice from the logs

  • For /path/one, node is looking for the file at the location /path/css/css-file.css and not at /css/css-file.css

From express docs for express.static

The function determines the file to serve by combining req.url with the provided root directory.

Thanks in advance for your help

1 Answers

WORKAROUND

Found a workaround for this.

Looking at the logs and the network calls, for the css, the following call is being made for fetching the css file

GET /path/css/css-file.css 

This call fails with a 404, resulting in the css not being used for the html.

I added a new route in the server, as below

app.get(`path/css/:fileName`, (req, res) => {
   const fileName = req.params.fileName;
   const filePath = path.join(__dirname, `./public/css/${fileName}`);
   res.set({'Content-Type', 'test/css'})
   res.sendFile(filePath);
}

This returns the CSS file from the desired path, and ultimately being used by the HTML file.

This seems to be just a workaround, and not a solution from within express.static.

Hope that someone would provide a solution here.

Thanks in advance!!

Related