Images are not being successfully retrieved by Express.static from the public folder

Recently, it seems that Express is having trouble pulling images from the image folder in the public directory, even though it can successfully retrieve the styles.css file located in the css folder within the same public directory.

The public directory consists of two distinct folders - one designated for css files and another specifically for images.

I attempted to address this issue by including the line of code:

app.use(express.static('images'));

to directly target the image folder within the public directory. Unfortunately, this approach did not resolve the problem. While linking to images with a URL works fine, accessing images from the directory itself does not seem to be functioning as expected.

I would greatly appreciate any assistance or guidance on this matter. Despite conducting extensive searches online, I keep receiving the same recommendation to use express.static. Additionally, I experimented with adding __dirname before 'public' but encountered errors in the process.

Below is an excerpt from my server code:

const express = require("express");
const bodyParser=require("body-parser")
const ejs = require('ejs');


const app = express();


app.set("view engine", "ejs");

app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static('public'));


app.get("/", function(req, res){
    res.render("index");
});

app.get("/prices", function(req, res, ){
    res.render("prices");
});

app.get("/about", function(req, res, ){
    res.render("about");
});
app.get("/contact", function(req, res, ){
    res.render("contact");
});

const PORT = process.env || 3000;

app.listen(3000,function(){
    console.log("server started")

});

Additionally, here is a snippet of my HTML template (header.ejs). The logo should be displayed here, however, it is currently not visible.

In an attempt to utilize the __dirname, I implemented it in the following manner:

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

Answer №1

Initially, there is no requirement for the full path in the src attribute.

Additionally, white spaces are not allowed in the path.

Attempt modifying the path as follows and let me know if it functions correctly.

<img class="deltaLogo"  src="\images\1x\Asset%<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bb898b8dfb89c395cbd5dc">[email protected]</a>"
            href="#"></img>

Answer №2

When working with Express.js, it is important to remember that the views folder is primarily used for templates and does not have direct access to static files like images. Instead, static files should be stored in a public folder (or another specified directory) that can be accessed by Express.js. To properly display images from the public folder, you need to ensure that your Express application is set up correctly and that the paths in your views are accurate.

If your index.js file is located in a different folder from your views, you will need to include this line of code. Otherwise, simply specify 'views' after __dirname. app.set('views', path.join(__dirname, '/..views'));

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

JavaScript API for Tableau

Could you please clarify the functions described below? newViz = createTableauViz(containerDiv, url, options); function listenForMarkSelection() { newViz.addEventListener(tableau.TableauEventName.MARKS_SELECTION, handleMarksSelection); } funct ...

Ways to provide information to an rxjs observer

It appears that most people find observers to be a piece of cake, but I personally struggle with them. I am trying to set up an observable that can receive a number input after it has been created, triggered by pressing a button. However, all the examples ...

Encountering a peculiar error while attempting to install firebase-tools

Currently in the process of deploying my application on Firebase by following a tutorial. I encountered an issue after executing the command npm install -g firebase-tools: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" d ...

Customizing individual textareas in tinyMCE can easily be done by adjusting the

This resource provides instructions on customizing features like the menubar and status bar for all form fields within tinyMCE: tinymce.init({ selector: "textarea", menubar:false, statusbar: false, .. }); I am wondering how to achieve th ...

What could be causing my JavaScript code to not function properly in an HTML document?

Hello, I am a beginner in the world of coding and currently delving into web development. Recently, I was following a tutorial on creating a hamburger menu but I seem to be encountering some issues with the JavaScript code. I have double-checked my Visual ...

Is there a way to prevent Javascript from modifying styles when printing?

Is there a way to prevent JavaScript from affecting styling during printing? For example, if I'm using JavaScript to hide certain content but want that content to be visible when printed. I have hidden a div using JavaScript and now I'm trying ...

Responsive YouTube video player with adjustable width and fullscreen functionality

I am currently attempting to embed a YouTube video on my website bearblog. My objective is to make the video adaptable in width for both mobile and computer viewing, while also enabling the YouTube fullscreen feature. I have followed the guidelines provid ...

Guide on closing a Bootstrap modal by clicking within the UI Grid in Angular

I have an Angular app written in TypeScript where I am utilizing the ui grid to present data within a bootstrap modal. My goal is to have the modal close when any of the columns in a grid row are clicked. Currently, I am not relying on $modal or $modalIn ...

The XML information vanished during the transformation into JSON format

After converting XML to JSON using multiple conversion libraries, I noticed that the property name attributes and Item name attributes were lost. Why is this happening? Does anyone have suggestions on how I can modify my XML to make it more compatible for ...

Retrieve an item from a mapped array

Currently, I am using the following code snippet console.log('errors: ' + password.get('errors')); to check the output from password.get('errors'));, and in the console, the response is as follows: List [ Map { "id": "validat ...

Verification of symmetrical file formatting

When dealing with three separate file upload inputs, the challenge is to ensure that the uploaded files are not duplicates. Additionally, if the user selects image format files (such as png, jpg, jpeg), they must select all three inputs in image format. On ...

javascript issue with setting the id attribute on a select option

I can't seem to set the id attribute in my select element using JavaScript. When I inspect it, the id attribute isn't showing up... Here's the first method using JS: var selectorElem = document.getElementById('selector') var ...

recovering hidden components within an object

I've come across a data structure that contains embedded objects, presenting an interesting challenge: var object = { 'A' : {'cc' : { 'cc data 1' : 'data 1 cc for A', ...

What is the method for configuring Vue to utilize a value other than the value property in form fields?

I am facing a unique challenge. Consider this: <select name="screw[type]" v-model="form.screw.type"> <option value="My value" ><?php _e('My value', 'fiam'); ?></option> //[...] Now, in another part of my ...

Having trouble getting datatables.net to function properly with JavaScript

I've been experimenting with datatables from http://datatables.net/ Attempting to make it work using javascript, but I'm facing issues. Even when following the example provided on the website, it still shows a blank page. Does anyone have any su ...

What is the process of creating and customizing popovers in Bootstrap 5 with jquery?

Is there a way to dynamically create and add content to Bootstrap 5 popovers using JavaScript or jQuery? In Bootstrap 3, I used the following method: $('#element').popover({ placement : 'left', trigger : 'focus', html: true } ...

String passed instead of JSON in Ext JS grid sorting

I encountered an issue while attempting to incorporate server-side sorting with Sencha Ext JS. The JSON paging section appears correct, but the sort property is defined as a String rather than an Array: Actual: {"page":1,"start":0,"limit":50,"sort":"[{&b ...

Utilize Dinero.js to implement currency formatting for input fields in React applications

I am currently working on a form in React that requires certain input fields to be formatted as money currency. These inputs should be prefixed with the dollar sign ($), include commas for thousands separation, and have exactly two decimal points. During ...

Modifying a $scope variable beyond the controller in AngularJS

I am trying to update a variable called $scope.outsidescope outside of the controller in my AngularJS application. The routing is done using $routeProvider, and the $scope.outsidescope variable is located outside of the ng-view. My query is how can I modi ...

I am curious as to how this function is aware of the specific attribute that is being passed

I've been experimenting with a little application that fetches a list of movies from an API. You input a word and it returns all movies with that word in the title. Here's the code responsible for fetching the list: var getMovies = function (que ...