Creating static directories and sub-directories simultaneously with express.js

I have a `views` directory that I made static by using `app.use(express.static('views'))`. The views directory consists of subfolders as listed below-

views
|-homepage/
|    |-homepage.ejs
|    |-homepage.css
|    |-homepage.js
|
|-partials/
|     |-navbar.ejs
|     |-footer.ejs
|
|-playground/
|    |-playground.ejs
|    |-playground.css
|    |-playground.js

I rendered the homepage and noticed that the CSS was not displaying correctly, because I did not specify `./views/homepage` as static.

Although it is currently not an issue since I only have a few pages to render, if in the future I plan to create dynamic directories, I am unsure how to make their respective folders static.

Is there a way to declare a folder as static and have all its subdirectories automatically become static as well? I have heard people mention that once the parent folder is marked as static, all subdirectories also become static which makes sense, as my homepage.ejs was displayed properly (albeit without CSS), but I had to specifically add `app.use(express.static('./views/homepage'))` for the CSS to render on my homepage.

Thank you in advance!

Answer №1

To properly serve static files like CSS and JS, it is a common practice to store them in a designated directory, such as public. Take a look at this illustration.

https://i.sstatic.net/CxI26Prk.png

In your primary configuration file (e.g. app.js), you must set up express to serve static files from the public folder:

app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
// sample route
app.get('/', (req, res) => {
    res.render('homepage/homepage');
});

In your .ejs files, ensure to reference the corresponding CSS and JS files with the correct path to the static files. For instance, in homepage.ejs:

https://i.sstatic.net/AzmBgv8J.png

Hopefully, this approach proves effective for your project.

Answer №2

When trying to access files in sub-directories, it is important to make sure that the URL path is relative to the root in express.static.

The following code example will successfully load the file as the URL path is properly relative to the root:

//server.js
app.use(express.static('views'));

//homepage.ejs
<link rel="stylesheet" href="/homepage/homepage.css" />

In contrast, the next code snippet will not be able to load the CSS file because the URL path is not correctly specified:

//homepage.ejs
<link rel="stylesheet" href="/homepage.css" />

However, the following code will work as there are multiple directories set up to serve static files, and the root specified in the second express.static call will handle the referenced file:

//server.js
app.use(express.static('views'));
app.use(express.static('views/homepage'));

//homepage.ejs
<link rel="stylesheet" href="/homepage.css" />

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

How do I designate the compiled migration location?

Currently, I am utilizing the PostgreSQL database ORM Sequelize along with TypeScript as a backend script within the Express Node.js environment. My first inquiry is: Is it possible to directly create a model in .ts format? The second question pertains t ...

The sequence of CSS and deferred JavaScript execution in web development

Consider this scenario: you have a webpage with a common structure in the <head>: <link rel="stylesheet" href="styles.css"> // large CSS bundle <script defer src="main.js"></script> // small JS bundle with defer attribute There is ...

The correlation between the node.js version and the @types/node version

I recently started exploring node.js and decided to experiment with using TypeScript alongside it. After running npm install @types/node, I found that the latest version available was 7.0.4: $ npm install @types/node <a href="/cdn-cgi/l/email-protectio ...

Exporting a node express app for chai-http can be done by creating a module

I have set up an express app with multiple endpoints and am currently using mocha, chai, and chai-http for testing. Everything was running smoothly until I added logic for a pooled mongo connection and started creating endpoints that rely on a DB connectio ...

What is the best way to add animation to my `<div>` elements when my website is first loaded?

I am looking for a way to enhance the appearance of my <div> contents when my website loads. They should gradually appear one after the other as the website loads. Additionally, the background image should load slowly due to being filtered by the wea ...

Are there any alternatives in NodeJS similar to PyAutoGUI that have the ability to search for an image within a screenshot?

I've been working on developing a bot to automate tasks in a video game using JS and Node, primarily utilizing RobotJS. However, I'm encountering an issue where I need to locate and click on a moving element on the screen, similar to PyAutoGUI&ap ...

Unrestrained text

I have created a simple layout. http://jsfiddle.net/kK7Rk/ HTML <div id="container"> <div id="logocontainer"> </div> <div id="navigationcontainer"> </div> <div id="t ...

The intl-tel-input dropdown feature is malfunctioning on mobile browsers

Currently, I have integrated the intl-tel-input library into my project for selecting international telephone numbers from a dropdown menu. https://i.sstatic.net/vPfpd.png While accessing the application on a web browser, the country flags display correc ...

Encountering an Issue with React, Node Js, and Express - Unable to Access / Endpoint

I'm encountering an issue when trying to access my app. The app was created using create-react-app with nodejs and express on the backend, and can be found at "colorsofemre.com". However, whenever I attempt to make changes to the app, all I see is a C ...

Gain access to Google Analytics without the need for page consent by utilizing JavaScript

I am currently building a dashboard with Atlasboard. My goal is to retrieve Google analytics data such as page views, and I plan to run specific queries which can be found here. Is there a method to access my Google analytics data without the consent pag ...

Navigating the world of CSS with Razor

Utilizing Razor for the creation of a dynamic website, I have set up my _siteLayout.cshtml file where I defined the header, footer, and the body section to be replaced by @RenderBody() <header> </header> <section id="content" class=" clear ...

The expression req.files consistently comes back as an empty [object]

I have been encountering an issue with saving uploaded files using their original names (with express-fileupload). Whenever I upload a file, it gets saved in the directory as [object Object]. Node: var express = require('express') var app = exp ...

Retrieve information from the MongoDB database using Node.js

I have developed a login system using Node.js and currently only able to retrieve the token from JWT. However, I also need to fetch the username, _id, and mobile number along with the token, which are already stored in the database. Can someone guide me on ...

Achieving proper alignment for the Mega Menu within the designated container

I have implemented a Mega Menu using Bootstrap 5. The menu is currently positioned on the left side due to the CSS styling: @media (min-width: 992px) .navbar-expand-lg .navbar-nav .dropdown-menu { position: absolute; } If you'd like to see t ...

Ways to extract specific HTML from a jQuery element

When fetching html from a website, how can I extract specific html content instead of getting all of it? I have attempted the following method: Before appending data to the target below container.html(data); I would like to perform something like data.f ...

What should be my approach to dealing with the "cancel" intent while currently engaged in a conversation?

Within the Microsoft Bot Framework, I have initiated a conversation and am currently running an intent called "login". However, in the midst of prompting the user for their username or password, they may unexpectedly request to "cancel that" or "cancel l ...

Arrange the image in a way that flows smoothly with the text

I want to achieve the effect of having a picture of a Pen positioned behind the text "Create" on the left side. It looks good at full size, but the positioning gets messed up when the screen size is adjusted. How can I make it responsive so that the image ...

Adjust the Material UI Select component to accommodate the length of the label

Is there a way to automatically adjust the size of Material-UI's Select input based on the label? In the official demo, minWidth is added to the formControl element. However, I have multiple inputs and do not want to set fixed sizes for each one. Whe ...

Forwarding information and transferring data from a Node server to ReactUIApplicationDelegate

I am currently working on a NodeJS server using Express and React on the front-end. I am trying to figure out how to send data from the server to the front-end without initiating a call directly from the front-end. The usual solutions involve a request fro ...

Position the colored div on the left side of the page

Here is the CSS I am currently using... <style type="text/css"> .widediv{width:1366px;margin-left:auto;margin-right:auto} </style> This CSS code helps me create my webpage : <body><div class="widedivv"> <!-- Content go ...