Alonso Tan
Alonso Tan

Reputation: 39

CSS background image is not loaded on localhost using Node.js

I have tried many of those solved examples, but I am not able to solve the problem. Everything is showing on localhost except for the background image. I have used sendFile() for referencing style.css file.

test.js

var express = require("express");
var app     = express();
var path    = require("path");
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static('image')); //I am not sure about this line.


app.get('/index.html',function(req, res){
res.sendFile(path.join(__dirname+'/index.html'));
});

app.get('/style.css', function(req, res){
res.sendFile(path.join(__dirname+'/style.css'));
});

style.css

.container-home {
width: 100%;
height: 30em;
display: flex;
flex-direction: column;
transition: background-size 2s ease-in-out 1s;
background-image: url(image/Greenery.jpg);
background-size: 100%;
background-position: center;
position: relative;
}

File Structure

Code
 |_ tree
      |_ image
          |_ Greenery.png

Upvotes: 0

Views: 1450

Answers (2)

T J
T J

Reputation: 43156

From the docs:

Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL.

So in your case, since you are making images the static directory, it shouldn't be in the URL. Your CSS is currently including it: localhost:3000/image/Greenery.jpg. .

I'd change background-image: url(image/Greenery.jpg); to
background-image: url(Greenery.jpg);


Or you can try creating a virtual path prefix like this without editing the CSS:

app.use('/image', express.static('image'))

Also note this part:

However, the path that you provide to the express.static function is relative to the directory from where you launch your node process. If you run the express app from another directory, it’s safer to use the absolute path of the directory that you want to serve:

So in your case it should be something like:

const path = require('path')
app.use('/image', express.static(path.join(__dirname, 'tree', 'image')))

Upvotes: 1

Sarkar
Sarkar

Reputation: 1879

change you project structure to something like this

--- root
  --- server.js
  --- public
   --- styles
     --- style.css

now change you static line to this

app.use(express.static('public')); // this tells express serve static assets here to the user

now when you navigate to localhost/styles/style.css you get you css file and you don't have to specify a route for it so you can remove this from you code

//remove this
app.get('/style.css', function(req, res){
res.sendFile(path.join(__dirname+'/style.css'));
});

Upvotes: 0

Related Questions