Home > OS >  When sending html file using Express.js app.get() method CSS and JS located in external files are no
When sending html file using Express.js app.get() method CSS and JS located in external files are no

Time:10-17

Please note that I read the following StackOverflow post and it did not help: Stylesheet not loaded because of MIME type

I can create a static public folder using Express.js where the index.html can recognize the style.css and tool.js files (located in the public subfolders of css and js, respectively). I used this line in the index.html file:

<link rel="stylesheet" href="css/style.css">
<script src="js/tool.js" defer></script>

and this line in app.js:

app.use(express.static("public"))

Ok: This works. Now, I do not want to use a static folder and want to handle the requests one by one. So instead of defining an express static public folder, I use the following line:

app.get("/",(req,res) => {
    res.sendFile('./public/index.html', {root: __dirname})
})

Please note that I removed app.use(express.static("public")) from the code at this stage.This works for deploying the index.html (located in the public folder), but the index.html file does not recognize the CSS style sheet.

I tried the following alternatives for the CSS file path:

<link rel="stylesheet" href="public/css/style.css">
<link rel="stylesheet" href="/public/css/style.css">
<link rel="stylesheet" href="./css/style.css">

Similarly, I tried alternative paths for tool.js, for example:

<link rel="stylesheet" href="/public/js/tool.js">

which did not work.

This is a sample of the error messages:

Refused to apply style from 'https://www.example.com/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. www.example.com/:9 GET https://www.example.com/js/tool.js net::ERR_ABORTED 404 (Not Found) www.example.com/:1 Refused to execute script from 'https://www.example.com/js/tool.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

Ultimately, I put the style.css file and tool.js next to index.html file with the following link paths:

link rel="stylesheet" href="style.css">

which did not work and showed that getting the path to the css and js files was not the primary problem, given that I got the same above-mentioned error messages.

How can I fix this without using app.use(express.static("public")).

CodePudding user response:

How can I fix this without using app.use(express.static("public")).

You could write an explicit route for every single file you want to serve, just like you did for /.

So you'd need:

app.get("/js/tool.js",(req,res) => {
    res.sendFile('./public/js/tool.js', {root: __dirname})
})

… etc.


Note that the static middleware does more than simply serving files. It also handles things such as setting sensible HTTP headers that aid caching. I strongly recommend using it over sendFile.

  • Related