Having trouble displaying image using absolute path in Express

Currently, I am developing a NodeJS application and have encountered an issue with a div element that has a background-image set in an external CSS file. Surprisingly, the CSS file functions perfectly when tested independently, and the background image displays correctly when viewing the HTML without Node.

The CSS code snippet:

#schoolInfo {
  display: block;
  background-image: url('slide1pic.jpg');
  background-repeat: no-repeat;
  width: 100%;
  height: 100%;
  background-size: cover;
}

Snippet from app.js:

var express = require('express');
var app = express();
var serv = require('http').Server(app);
var io = require('socket.io')(serv);
var path = require('path');

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

app.use(express.static('client/home'));

app.post('/createSchool', function(req, res) {

  app.use(express.static('client/school'));
  res.sendFile(path.join(__dirname, '/client/school/index.html'));

  io.emit('updateSchool', response);
});

serv.listen(3000);
console.log("Server started on localhost://3000");

Even though the URL is absolute, it appears that Express cannot locate it. Oddly enough, there are no errors reported in the Command Prompt (where the server is executed) or in the browser console.

Is there something missing in my app.js file? Any insights or assistance would be highly appreciated.

Answer №1

Make sure to include the correct routing in your URL when serving files:

app.use('/', express.static('client/home'));

The path '/' is relative to the location where your node process starts.

If you have an index.html file in your home directory, you can create an images folder there and update your express.static() like this:

app.use('/images', express.static('client/home'));

In your HTML file, simply use:

<img src="images/file.png" />

To run your node process correctly, start it from:

client\home > node server.js

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When I try to refresh the Heroku page, all I see is the API information and not

I recently launched a PERN stack application on Heroku. Everything seems to be running smoothly, but I encountered an issue when trying to refresh the page at this specific URL - - as it only displays API information: { "id": 1, "title": "Earth Nights #1 ...

Unsuccessful attempt at testing RequireJS in a straightforward manner

As a beginner in RequireJS, I am currently experimenting to gain some experience. My goal is to make require load basic Angular first and then manually bring in Angular UI Bootstrap. However, I am encountering an issue where UI Bootstrap complains that ang ...

Strong tags within MFC

Is it possible to create labels in MFC (Static text) that contain both bold and non-bold text? For instance, something like this: "I want my label to have a mix of styles like this" Any suggestions on how to achieve this? I am aware that I can change ...

Tips for obtaining the precise status code of the response following a model.save operation in Backbone.js

When using backbone js on the front end, I have the following code snippet: this.model.save() .success(function (data) { console.log("Received response: " + JSON.stringify(data)); }) .error(function (error) { co ...

Finding JPG images using Jquery selector

I am looking to utilize jQuery to specifically target <a href=""> elements that have 'href' attributes with file extensions '.JPG' or '.jpg' For instance: To only select these 'links' <a target=& ...

Encountered an issue while attempting to initiate Ionic start: An error occurred during the execution of the following command: npmin

Currently, I am in the process of developing a mobile application using Ionic and Cordova. However, whenever I try to initiate the following command: ionic start {{appname}} blank Upon completion of the download, npm throws an error stating: Error with ...

Is it possible for an Electron window to utilize Windows authentication for SSO login?

Currently, I am working on an early stage Electron application that is being used for a proof of concept. One specific challenge I have encountered involves the use of mainWindow.loadURL('https://example.com'); in my code to open our internal app ...

Try utilizing the Array.map method with a two-dimensional array

My current challenge involves a 2-dimensional Array where I am attempting to implement a "randomBool" function on each of the elements within it. The "randomBool" function essentially generates a random boolean value: const randomBool = () => Boolean( ...

Transform post-back into PHP using JSON for Ajax posting

Currently, I am facing a challenge in integrating a Codeigniter application into Wordpress using a plugin. The trouble arises when the control encounters an issue while confirming the data for a new appointment. VIEW <div id="wizard-frame- ...

Checkbox fails to trigger onChange when the checked value is controlled by state management

Currently, I am working with a material-ui Table and have been in the process of implementing multi-select functionality on it. The behavior I am aiming for my multi select to exhibit is as follows: Checkboxes should only appear at the beginning of a ro ...

Error: Unable to initialize monthSelectPlugin as a constructor while trying to utilize the Flatpickr plugin

I'm trying to incorporate the monthSelectPlugin for flatpickr in a Rails application. I have it specified in my importmap like this: pin "flatpickr/dist/plugins/monthSelect", to: "https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/emai ...

Showing a PDF file within a Bootstrap modal

I'm encountering difficulties with a simple task. My goal is to display a PDF using the HTML <object> tag within a Bootstrap modal. I've put together a Plunkr to illustrate the issue. Essentially, there is a straightforward <object> ...

Make the background image come to life by animating it from the bottom to the top in

Upon landing on a page, I aim for the background image to initially focus on the bottom and then pan up to the top before returning back down in a continuous loop. The code I have set up is as follows: <body> <div id="container"></div&g ...

How can child components in ReactJS be conditionally rendered based on the status of userData loading?

It seems like there might be an issue with how we handle user login in our application. Whenever a user logs in, the redux state is updated with the server response. Many components rely on this logged-in status. We pass the currentUser object down to all ...

What is the best way to incorporate a class creation pattern in Typescript that allows one class to dynamically extend any other class based on certain conditions?

As I develop a package, the main base class acts as a proxy for other classes with members. This base class simply accepts a parameter in its constructor and serves as a funnel for passing on one class at a time when accessed by the user. The user can spe ...

When utilizing a reverse proxy with Nginx, an error stating that "TypeError: res.end is not a function

Running nginx and pm2 concurrently on my server. I configure nginx to act as a reverse proxy for my API (PM2). # Proxying API connections to api location /api/ { proxy_pass http://localhost:3000/api; proxy_http_version 1.1; proxy_set_header H ...

"Troubleshooting problem with padding-right in Internet Explorer when displaying background image within

Encountering a problem with the IE browser (all versions up to IE 10). Here's the issue. The text in the input box is overlapping its background image. Unable to place this image in the parent div due to the dynamic nature of the input box and other ...

Adjusting the Height of the Video Jumbotron in Bootstrap

One of my main goals is to create a jumbotron with a video that plays, occupying 100% width and 70% height of the screen. However, I am facing an issue where the video follows the scrolling behavior when I don't want it to. Specifically, as I scroll d ...

Form submission is failing due to a single checkbox not being submitted and an error is occurring with MultiValueDictKeyError during

<body ng-app=""> {% extends "pmmvyapp/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block content%} <div class="col-md-8"> <form method="post" action="/personal_detail/"> {% csrf_token %} <div class="form-group" ...

The Axios GET request was not functioning properly after attempting to use Axios stream.on("data")

I am working with a backend API that has an endpoint named /subscribe, which gives back a continuous stream of data. Along with this, I have a node process, and I am utilizing axios to send a request to my backend API with a response type of "stream& ...