The issue seems to be with the loading of CSS when using req.params, but it

I am just starting out with node, express, etc. and have created a blog app. However, I am encountering an issue. My application utilizes mongoose, node, express, and ejs.

When I make the following call:

router.get('/posts', function(req, res){   
    Post.find({}, function(err, posts){
        res.render('viewpost.ejs', {
            posts
        });   
    }); 
});

Everything functions correctly. I am able to retrieve my posts and the CSS styling works as expected. The problem arises when I use:

router.get('/posts/:posts_id', function(req, res){
    Post.find({_id: req.params.posts_id}, function(err, posts){
        res.render('viewpost.ejs',{
            posts
        });
    });
});

The post retrieval works fine, but in the console I see:

GET /posts/posts.css 304 1.854 ms And it appears that the viewpost.ejs file is not applying the CSS styles.

Within the server file server.js:

app.use(express.static('public'))
app.use(express.static(path.join(__dirname, 'public/css/')));
app.use(express.static(path.join(__dirname, 'public/img/')));

In the viewpost.ejs file:

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.css"/>
    <link rel="stylesheet" href="style.css">
    <script src="/bower_components/jquery/dist/jquery.js"></script>
  </head>
  <body class="cyc">
  <% include ./partials/navbar.ejs %>

<%= posts %>
</body>
</html>

It seems that everything works fine when I use the route without parameters. However, as soon as I include any parameter, my CSS file stops working correctly.

Answer №1

<link rel="stylesheet" href="style.css">
attempts to fetch the style.css file from the same location as the HTML page it is on. This means that for the URL path /posts, it will look for /style.css, and for /posts/1, it will try to find /posts/style.css. However, this could lead to confusion because /posts/:posts_id can be mistakenly triggered by a request for style.css, resulting in an unexpected behavior.

The solution is simple: use an absolute link instead:

<link rel="stylesheet" href="/style.css">

Answer №2

After experiencing a similar dilemma, I persevered until I found a solution. Here's what worked for me: Within your HTML or EJS file, add the following code snippet to the head section:

<link rel="stylesheet" href="../style.css">

This should resolve the issue for both /post and /post:id routes.

Answer №3

Here's what I usually do:

Instead of:

<link rel='stylesheet' href='style.css'>

I change it to:

<link rel='stylesheet' href='/style.css'>

Simply include the /.

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

The sticky navigation bar is not returning when scrolling up, and the function to remove the class is not working properly

After implementing a navigation bar that works on scroll down, I ran into an issue where it doesn't stop at the original position on scroll up. Despite finding a similar post addressing this problem, I struggled to apply the solution correctly due to ...

Navigating CSS imports when implementing server-side rendering in React

This situation is somewhat similar to another question about Importing CSS files in Isomorphic React Components However, the solution proposed involves a conditional statement that checks if the import is being done from the server or the browser. The iss ...

What is the best way to align dynamically generated divs seamlessly together?

After creating a function that generates a grid of divs placed in a container div upon document load or user reset, I noticed a gap between each row of divs. I aim for a flawless grid where each square aligns perfectly with the next. Despite trying vario ...

Ways to avoid an infinite loop caused by onAuthStateChanged Firebase Authentication

I have a provider setup that initializes the authentication context from Firebase Auth. Everything is working well, but when I tried to introduce persistence by adding an observer with onAuthStateChanged, it caused an infinite loop. Despite including an u ...

How can I position the dropdown to the right-hand side of the card header in HTML?

How can I position a dropdown in the top right corner of my card header? I want to have a welcome message on the right side of the card header next to the title, similar to the image below: https://i.sstatic.net/G0Sq3.png ...

Is there an easy method for extracting URL parameters in AngularJS?

Hello, I'm new to Angular and coming from a background in PHP and ASP. In those languages, we typically read parameters like this: <html> <head> <script type="text/javascript"> var foo = <?php echo $_GET['foo&apo ...

Ensure that the React Material UI Textfield with the type "number" is validated to have exactly 10 characters

<TextField variant="outlined" required fullWidth id="accno" label="Main Account Number" type="number" name="accno" //inputProps={{ className:"input-acc", pattern: "^.{0,10}$"}} autoComplete="accno" onChange={(e) = ...

Guide on notifying the client when the database is updated, similar to the notification system used in Facebook chat

Is it possible to send an alert to the client using the website only when a specific field is updated? I understand how to periodically check for database updates with silent Ajax calls, but I am looking to trigger an Ajax call only when relevant informa ...

How can you resolve redefinition warnings detected by the CSS Validator?

After running my site through the W3C CSS Validator, I was surprised to see that it returned a total of 3146 warnings. The majority of these warnings are redefinition alerts, such as: .fa.fa-check Redefinition of color .fa.fa-check Redefinition of ...

Can one select a garbage collection algorithm within GWT or any other JavaScript framework?

Is it feasible to select a garbage collection algorithm programmatically or through other methods (such as specifying the GC algo for the JVM) in JavaScript or any JS frameworks? ...

The response received from the JavaScript API was a blank PDF document

I am currently using handlebars and puppeteer to dynamically generate a PDF report on my express API/server. When I trigger the API using Insomnia, it returns the complete PDF exactly as expected. However, when I try to download the PDF from my client-side ...

Having difficulty in getting rid of the horizontal scrollbar

I need help replacing the horizontal scrollbar with arrow buttons to scroll through images (not the entire page). This is the code I tried: .scroll-images::-webkit-scrollbar{ -webkit-appearance: none; } However, the scrollbar is still ...

Access the modal by simply clicking on the provided link

I have implemented a code snippet below to display data from MySQL in a modal popup. Everything is functioning correctly, but I am interested in triggering the modal by clicking a link instead of a button. Is it feasible to achieve this considering I have ...

Retrieve the script's location from the server prior to the initialization of Angular

Is there a way to dynamically add a script in the index.html page based on the application version? I have a controller that retrieves the app version and attempted to achieve this using AngularJS: var resourceLoader = angular.module('MyTabs&apo ...

Concealing a message within a section that has been minimized to a width of 0

Recently, I've encountered a challenge in attempting to set the width of a section to 0 and have all its contents also disappear. Despite changing the section's width to 0px, the text inside continues to be displayed and even shifts off to the si ...

Instructions for utilizing HTML2PDF to create and deliver a PDF file to PHPMailer through Ajax

Trying to send a pdf generated from html2pdf (JavaScript - Erik Koopmans) to phpmailer via Ajax. Currently able to save the document to the local user's PC, but need help attaching it to an email using phpmailer. Successfully generating the pdf for s ...

Encountering a syntax error while attempting to import modules from amCharts

Recently, I have been attempting to incorporate amcharts into my project using npm. After running the command npm install@amcharts/amcharts4, I noticed that all the necessary modules were now present in my node_modules folder and package.json file. Specifi ...

Utilizing Jquery to pass two classes along

I am looking for assistance on how to pass multiple classes within if-else statements and jQuery. My goal is to have both divs and divs2 change when the next button is clicked. Can someone please provide guidance on achieving this? --code not mine-- ...

Detecting the browser through @media

While working on an existing website, I am tasked with staying within the current boundaries. As I introduce a new feature, I realize that we already have several @media blocks in the CSS file. In order to maintain consistency, I have applied styling that ...

Creating a JavaScript function to imitate the pressing of the Enter

I am attempting to mimic the pressing of the Enter key using JavaScript within a specific TextArea. Below is the code I have written: function enter1() { var keyboardEvent = document.createEvent('KeyboardEvent'); var initMethod = ...