Home > Enterprise >  Image not loading while using express
Image not loading while using express

Time:03-31

I have been trying to access my css and jpeg file from the assets folder but when I execute my express.js file the console throws this error

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

This is my express.js file

var express=require('express');
var path = require('path');
var bodyParser=require('body-parser');
var app=express();

app.use(express.static(path.join(__dirname,'assets')));
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

app.get("/",function(req,res){
  res.send("Welcome to my node express app");
});

app.post("/show_user",function(req,res){
  console.log(req.body.username);
  res.json({username: req.body.username})
});

app.get("/home",function(req,res){
   res.sendFile(__dirname "/express.html");
})
app.get("/about",function(req,res){
   res.send("Welcome to about us page");
})
app.get("/contact",function(req,res){
   res.send("You are now in contact us page");
})
app.listen(4000,function(){
  console.log("Server is running");

})

This is my express.html file

<html>
    <head>
        <title>Home page</title>
        <link rel="stylesheet" type="text/css" href="./assets/style.css">
    </head>
    <body>
        <p>Hello Glad to have u here</p>
        <img src="./assets/home.jpeg" width="100"/>
        <form action="show_user" method="post">
            <p><input type="text" name="username" placeholder="Enter Username"/></p>
            <p><input type="submit" value="Submit" name="submit"/></p>
        </form>
    </body>
</html>

This is what the directory looks like

CodePudding user response:

Change from this:

href="./assets/style.css"
src="./assets/home.jpeg

to this:

href="/style.css"
src="/home.jpeg"

You don't want to use path relative URLs here. You want all your CSS URLs to start with / so the browser won't append anything to the path-relative URL before it makes a request to your server.

  • Related