What steps should be taken to correct the CSS stylesheet path in an Express and EJS project?

Recently, I utilized Express and EJS for a project of mine. My goal was to have a .ejs file rendered when accessing "localhost:PORT/posts/:articleName". However, I encountered an issue even though I included the line

app.use(express.static(__dirname + "/public"));
. The problem lies in the fact that when inspecting the stylesheet link within the post.ejs file, it displays as "localhost:PORT/posts/style.css" instead of "localhost:PORT/style.css", which is necessary for proper functioning. How can I rectify this path discrepancy?

Here is the structure of my project: https://i.sstatic.net/DRkNw.jpg

The following code pertains to the GET request for /

app.get("/posts/:articleName", (req, res) => {
for(obj of posts) {
    if(lodash.lowerCase(obj.title) === lodash.lowerCase(req.params.articleName)) {
        console.log("it's a match");
        res.render("post.ejs", {title: obj.title, 
            content: obj.content});
        return;
    }
}
res.redirect("/");
});

posts = array of JSON objects

post.ejs = the file containing only specific articles. Unfortunately, it fails to load the style.css file from the public directory as intended.

Answer №1

Consider using this alternative approach, as the code snippet provided contains an error:

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

Answer №2

It seems that in order to get the correct path, you must include a "/" before your CSS file or place it in a different subdirectory.

Therefore,

link rel="stylesheet href="/style.css"
will function correctly, while
link rel="stylesheet href="style.css"
will not.

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

Obtaining the access token from the URL: A step-by-step guide

Once I have successfully authenticated with Google, the URL I receive is: http://localhost:3000/_oauth/google#access_token=ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw&token_type=Bearer&expires_in=3600 I am tryi ...

JavaScript client side event that references the sender object ID in an aspx file

Can someone provide assistance with an issue in the code block below? function(s, e) { form1.hfRaiseEvent.value = s.ID; } This particular function is triggered when the Client Side Click Event occurs. From my understanding, s refers to the Sender Obj ...

Using jQuery to dynamically add options to a dropdown list and trigger a change

$('.add').on("click", function () { $('.selects').append('<select><option value="1">Added 1</option><option value="2">Added 2</option></select>'); }); $(".selects se ...

Assistance required for posting Jquery files

Attempted to upload a file using jQuery with a hidden form and an Input element, triggering the file browser with jQuery. The changed input is then sent to a PHP server script. Encountered an issue where submitting the form with $("form1").submit(); worke ...

Setting initial opacity for CSS on page load

I'm not a pro at web design, but I'm trying to create my own website. I've divided my page into two sections - the left side for the menu bar and the right side for content. To add a 'cool' blur effect over my menu bar, I decided t ...

Is there a way to conceal form fields for city and state until the zip code is provided?

Is there a way to only display the city and state form fields after the zip field has been filled out? I have a geo-based program that automatically fills in the city and state based on the zip code entered, but I want to hide these fields until the data ...

Is there a way to compress my JavaScript and CSS files using gzip?

I am facing an issue with gzipping a prototype library. I have no idea how to go about it, where to start, and how it actually works. I tried looking at some tutorials but unfortunately, they weren't very helpful... So here's the setup: I have ...

Tables created in MySQL using Sequelize were initially given capital letters, however, Sequelize generates queries using lowercase letters

I am encountering an issue with my Sequelize migration. Sometimes, the Sequelize generated request is in lowercase like this: ALTER TABLE `organizations`... which results in the following error: ERROR: Table 'db_name.organizations' doesn' ...

Success with inserting data into MySQL, however the database table remains empty

I've encountered an issue with my React/MySQL registration page. Despite running the insert query, the data is not being inserted into the database table. I'm uncertain about what could be causing this problem. Within the backend folder, my serv ...

How can I showcase JavaScript validation messages on the screen instead of using alert messages?

In my project using struts 1.3.8, I've implemented the Struts ValidatorPlugIn to handle both client-side and server-side validation messages. Currently, the client-side JavaScript is generated by the validator plugin, which displays any validation e ...

Utilize ng-src in an Angular image tag when iterating through ng-repeat items

Using ng-src on img tags within ng-repeats has been successful for me in the past, but I'm facing difficulties with it this time. After making an API call that returns some data, I tried to display each item like this: <div ng-repeat="item in ...

The Javascript function was invoked, however the complete result was not yet delivered

I'm still a newbie when it comes to Meteor and Node.js, so what I'm struggling with might be a piece of cake for the more experienced developers out there. My task involves writing a script that aims to return the time 30 minutes into the future ...

I am interested in turning a div to complete a full 360-degree rotation

I am working on a layout where I have a square and inside it, a circle. The square is positioned absolutely and the circle is positioned relatively, centered within the square. However, when I rotate the circle using the rotate property, it loses its cente ...

Having trouble with a fixed element that won't scroll?

Code Example: <div id="tmenu" style="direction:rtl;"> <img src="assets/imgs/menu/all.jpg"/> <img src="assets/imgs/menu/sweets.jpg"/> <img src="assets/imgs/menu/main meals.jpg"/> <img src="assets/imgs/menu/ma5bozat.jpg"/& ...

Sending messages to a group on TELEGRAM without using a bot with JAVA/Node.js

I'm currently diving into the world of sending messages to a telegram channel without using a bot with JAVA. Although I am quite unfamiliar with the Telegram API, all the examples I stumbled upon require the use of a BOT. Is there anyone who can provi ...

Use the "webkit-keyframes" exclusively within the specified id

Is there a way to exclusively apply the "webkit-keyframes" within the #progress1 id? I have another progress bar (#progress2) on the same page with a different webkit-keyframes, which is why I need this distinction. #progress1 { background: white; / ...

What is the best way to utilize Union Types in v-model within a Vue component's :is directive?

I'm facing a TypeScript error while trying to bind the value of apiRes to v-model. Below is the code snippet where the error occurred. How can I resolve this issue? Arguments of type { modelValue: Cars | undefined; } cannot be assigned to type NonNull ...

Error: Attempting to access the `isPaused` property of a null object is not possible

For my Vue front-end app, I'm attempting to integrate wavesurfer.js. However, upon receiving the audio file link from the backend, I encounter the following error: wavesurfer.js?8896:5179 Uncaught (in promise) TypeError: Cannot read property 'isP ...

Utilize CSS to set a fixed position for a div based on its height

Hey there! Take a look at this piece of code: <div className="box-and-clock"> {isBoxShown && ( <div className="box"> {value} </div> )} <img ...

What is the best way to exit an if statement once the desired condition is satisfied?

In my code, I am checking a specific variable for conditions and modifying that variable within the code. How can I prevent the if condition from checking again once the condition is met? If the else-if condition is triggered and date2 becomes null, the ...