Issue with serving static files in ExpressJs

I'm facing an issue with my Express app where the static files are not working properly for certain routes. For example, when I visit '/', all styles and images load correctly as expected when the index.ejs is rendered. However, when I navigate to a non-existent route like '/efbhew', the 404.ejs page renders fine but the static assets do not load. Similarly, for routes like '/asdw/feff' or '/df/fg/dfgdfg/sfgd', the static resources fail to load. Is there something missing in my setup that I need to address?

Below is an excerpt from my code:

const app = express();
app.use(express.static(path.join(__dirname, '../public')));
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'ejs');
app.use(cors());
app.use(express.json());

app.get('/', async (req, res) => {
    const posts = await Post.find({}).limit(7).sort({ createdAt: -1 }).exec();

    res.render('index.ejs', {
        latestPosts: posts
    });
});


app.get('*', (req, res) => {
    res.render('404.ejs');
});

This is the current folder structure of my project:

I have attempted adjusting the path to the public folders to accommodate deeper paths such as '/asdf/wfds/img/logo.png', however, this did not resolve the issue.

Answer №1

When a ejs page located at /df/fg/dfgdfg/sfgd makes reference to a static file, such as:

<img src="img/logo.png"/>

The URL is relative to the URL of the ejs page, so in this scenario it would be /df/fg/dfgdfg/img/logo.png (notice how the last segment sfgd is omitted, which is why it functions for a page at /efbhew).

However, the image actually only exists at /img/logo.png. Therefore, it's recommended to always address it with a path that begins with a slash, like so:

<img src="/img/logo.png"/>

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

Youtube video embedding showing cut edges on smaller screens

Looking for assistance with a Next.js and tailwind site I am building. Having trouble getting the video component to display properly on mobile screens. Tried various fixes but the video still gets cut off on smaller screen sizes. If anyone has a soluti ...

Endlessly triggering document.execCommand, the JavaScript selectionchange-EventListener seems to have a mind of

I recently implemented an event listener for selectionchange in the following manner: document.addEventListener("selectionchange", function() { highlight(); console.log("selectionchange-triggered"); }, false); After that, I included the code bel ...

What kind of output should a Server Side Component generate?

Recently, I decided to incorporate the NextPage type from Next.js into my component writing routine after hearing it's a beneficial practice. However, I discovered that it only functions properly with client-side components. When attempting to utilize ...

The act of initiating a click on a radio button involves evaluating conditions prior to toggling

Apologies for the slightly ambiguous title, let me provide a clearer explanation. I have created a codepen to demonstrate an issue that I am facing. You can view it here. In my codepen, I have two toggle buttons labeled "Male" and "Female" for simplicity. ...

Can you provide instructions on integrating bootstrap 5.02 using npm and webpack?

Trying to bundle my webapp with webpack, but struggling with importing the bootstrap code. I've already spent hours troubleshooting this. Ever since setting up webpack, things haven't been working as they did before. And now, I keep encountering ...

"Learn how to transfer a selected value from a parent ASP.NET dropdownlist to a textbox in a popup window using JavaScript

I'm struggling to pass the value from a dropdown list in the parent ASPX form to a textbox in the child ASPX form. Parent JavaScript: The first script is used to open the popup window <script type="text/javascript"> var popup; ...

Use jQuery to trigger a click event when an element is in focus, unless it was clicked to

I am currently developing a website using the MDL framework. One issue I encountered is that there is no default select form element provided. After some research, I found a solution by utilizing a menu component that displays when the input is clicked. Th ...

Utilizing JSON format, handling special characters, and storing data in a database

My friend approached me with a question and although I wanted to offer immediate help, I realized that seeking advice from others may provide better solutions. Situation: Imagine there is a Form that includes a RichText feature: DHTMLX RichText (). This R ...

Retrieve a particular cookie from the request headers in Express framework

Today, I encountered a problem with express. Let's say we set multiple cookies, but when I check request.headers, only one cookie is returned: cookie: 'userSession=123' For instance, not only is it unreliable to use request.headers.cookie ...

Ensure data accuracy by triggering the cache - implementing SWR hook in Next.js with TypeScript

I recently implemented the swr hook in my next.js app to take advantage of its caching and real-time updates, which has been incredibly beneficial for my project (a Facebook clone). However, I encountered a challenge. The issue arises when fetching public ...

How to declare WinJS.xhr as a global variable in a Windows 8 Metro app

Currently, I am developing a Windows 8 Metro app and facing an issue with a hub page. The problem arises when pushing data dynamically from an XML API using two WinJs.xhr("url") calls; one for headings and the other for section datas. When merging both W ...

Sequelizejs establishes a belongsToMany relation with a specified otherKey

I am currently developing an app centered around songs and artists, and here is the database schema I have designed: Each Song can have multiple Artists associated with it, and each Artist can be linked to several Songs as well. This establishes a many-to ...

Tips on obtaining checkbox value in an AJAX request

I need to retrieve the value of a checkbox using Ajax in order to store it as a user preference in the database. This task is new to me, and I'm feeling a bit overwhelmed. Here is my JavaScript file: $(document).ready(function() { E.accounts.chang ...

Is there a way to display the next/previous buttons separately from the scroller in my jQuery thumbnail scroller implementation?

Is there a method to display the next and previous buttons outside of the scroller frame when using jQuery thumbnail scroller by manos.malihu.gr? I have attempted to modify the button class in CSS to make them more prominent or visible, but unfortunately ...

Error: Improper hook call detected with no hooks being used (material-ui v5)

I've created the following basic application: import Grid from '@material-ui/core/Grid'; function App() { return ( <div className="App"> <Grid container spacing={2}> <Grid item xs={8}> ...

How can UI tests be run in headless mode in Selenium 4 and above?

Selenium recently announced the release of Selenium 4, and they have also mentioned that there will be no support for PhantomJS from Selenium 4 onwards. Does this mean that Selenium no longer supports headless automation, or is there a different method t ...

I'm experiencing an issue where my drum app element does not refresh after performing an action dispatch

Struggling with my React/Redux drum app, I'm at a roadblock with the final component that should update with the selected object's ID through an action dispatch. It baffles me why the element won't reflect the changes even though I've c ...

Does every controller page need to verify the Login Function?

In my PHP pages, I have implemented the MVC Pattern by creating a controller page for each view page to interact with the Model page. However, I have only checked user login at the top of every view page and not in the controller page. This leaves a potent ...

What is the best way to execute a mongoose query within a forEach loop?

Looking for assistance on how to execute a mongoose query within a forEach loop in Node.js and get results from an inner join of two collections. Example: userSchema.find({}, function(err, users) { if (err) throw err; users.forEach(function(u,i){ ...

Unable to retrieve Vuex state within a function

Currently, I am developing a Laravel+Vue application where Vuex is used for state management. While working on form validation, everything seems to be progressing smoothly except for one particular issue that has me stuck. The problem arises when I attempt ...