Search code examples
node.jsexpressstatic-files

CSS and JS file not linking in node js


I want to use middleware func to serve static file,but the problem is that my css file is not linking with html file using node and express

error is:

Refused to apply style from 'http://localhost:4000/static/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

app.js:

const express=require('express');

const path=require('path');

const app=express();


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


app.get('/',(req,res)=>{

   res.sendFile(path.join(__dirname,'static','index.html'));

});

app.listen(3000);

index.html

<!DOCTYPE html>

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
   <link rel="stylesheet" type="text/css"  href="/static/css/style.css">
</head>
<body>
    <div class="asd">
          Hi xyz here..
          
    </div>
    <script src="/static/js/script.js"></script>
</body>
</html>

folder structure is:

 static

   css

     main.css

   js

     script.js

   index.html

 app.js

I tried a lot , but i am not able to find the error, please help!! Thanks!!


Solution

  • We will have to do something like that:

    app.js

    const express=require('express');
    
    const path=require('path');
    
    const app=express();
    
    
    app.use('/public', express.static(path.join(__dirname,'./static')));
    
    
    app.get('/',(req,res)=>{
    
       res.sendFile(path.join(__dirname,'static','index.html'));
    
    });
    
    app.listen(3000, () => {
      console.log("Starting at", 3000);
    });
    
    

    index.html

    <!DOCTYPE html>
    
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <script src="/public/js/main.js"></script>
        <link rel="stylesheet" href="/public/css/style.css">
    </head>
    <body>
        <div class="asd">
              Hi xyz here..
        </div>
        <script src="/public/js/script.js"></script>
    </body>
    </html>
    
    

    Here is the screenshot:

    Final Image


    A basic thumbs rule we can think of:

    app.use('<something_here>', express.static(path.join(__dirname,'./static')));
    
    <link rel="stylesheet" href="<something_here>/css/style.css">
    <link rel="stylesheet" href="<something_here>/css/style.css">