Dealing with a routing issue in node.js/express involving JavaScript and CSS

I'm facing an issue. I need to set up a route from localhost.../cars to localhost../bmw/x1

On the localhost../cars page, there's a button that, when clicked, should load localhost../bmw/x1

This is the JavaScript code I have:

const express = require("express");


var app = express();


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


app.set("views", "views");
app.set("view engine", "pug");

app.get('/', (req, res) => {
    res.render("firstpage");
});


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


app.get("/bmw/x1", function(req,res){
  res.render("bmwx1");
});

app.listen(PORT, function() {
  console.log("server is running);
});

In my pug file for the firstpage, I have the following structure (only part of the code):

html 
    head 
        link(rel="stylesheet", href="styles/style.css")
        link(href="https://fonts.googleapis.com/css2?family=Akshar:wght@300&display=swap" rel="stylesheet")
        meta(name="viewport", content="width=device-width, initial-scale=1, maximum-scale=1")
    body
        nav 
            h3 
                a(href="/cars") cars

And on the /cars page, there's a button like this:

div
   button(class="detailsbutton") 
          a(href="/bmw/x1") Details

Although everything seems to work fine, when I navigate to localhost../bmw/x1, the CSS doesn't apply properly only in that path, causing formatting issues.

I'm not certain if using app.get("/site/secondsite",...) is the correct approach or if the problem lies elsewhere.

Thank you for your help and apologies for any language errors!

Answer №1

When encountering a 404 error, it could be due to the absence of a / before your CSS link.

  • Adding a slash at the beginning of the styles indicates that it is being called from the root directory.
  • To resolve this issue, modify your link to href="‌/styles/style.css" and it should function correctly.

For further information, refer to this source.

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

Practical steps for programmatically adding or removing md-disable-backdrop in md-sidenav

Can the md-disable-backdrop attribute be removed from HTML? The issue arises when opening the side navigation as the md-sidenav does not have the md-disable-backdrop attribute. After making a selection from the form displayed in the side navigation, I now ...

Is there a way to execute code precisely at a specific timestamp?

I am working with a backend that has a REST API containing an array of objects with timestamps (indicating when events occur in the game) along with respective values. {"timestamp":1623320102097,"crops":[0,5,9]} Is there a way to trigg ...

Success is returned as AJAX error

My AJAX call is returning an error as Success instead of a JSON error from ASP.NET MVC. Can someone please advise on how I can resolve this issue? Thank you. [HttpPost] public JsonResult Register(int EventID) { try { ...

Forward the jsp to the servlet before navigating to the following page

Issue: After submitting the JSP form on Page1, it redirects to a server-side JSP page but appears as a blank page in the browser. Instead, I want it to redirect to Page2 which includes a list box that highlights the newly created item. Seeking help with t ...

Choosing the perfect item with the help of a material's GridList

I've developed a react-mobx application using Material-UI, and the code structure is similar to this: render() { // defining some constants return ( <div> <img src={selectedPhoto} alt={'image title'} /> < ...

Choose a particular text node from the element that has been selected

Can anyone provide guidance on how to extract the text "Items Description" from the following HTML snippet using jQuery? <div class="items"> "Items Description" <ul> <li>1. One</li> <li>2. Two</li&g ...

Incorporate a span element within the PHP code located in the final div

Having trouble with adding a span in PHP The last div is not functioning correctly. **In need of help on how to insert a span within PHP code.** echo" <tr> <td>$id</td> <td>$name</td> <td>$la ...

Navigating to another division segment within an HTML document using the arrow keys: a guide

There are three main div boxes colored pink, red, and green.  I would like to enable movement of all segments using arrow keys. When the page is loaded, the active box will initially be in the 'pink' segment at the center. We can then navigate ...

Personalize the position of the v-select drop-down menu

I am currently working with the vuetify v-select component. The problem I am encountering is that instead of the dropdown opening downwards, I need it to open upwards since the dropdown is positioned at the bottom of the page which causes some of the dro ...

Custom protocol gateway for TCP connections in Azure IoT Hub

Having recently started working with Azure IoT Hub, I've noticed that our devices do not support MQTT and instead send telemetry using simple TCP. I've come across discussions about custom TCP implementations for the gateway where we can adjust t ...

Tips for personalizing Bootstrap columns using identical class names?

Is there a way to customize the background color of each individual .col-5 within the same row while using Bootstrap and a custom CSS file? Changing the styles for one column seems to affect all columns with the same class name. Edit: I'm looking f ...

Unit testing Vue 3 by simulating the push() method of vue-router

As a newcomer to Vue and StackOverflow, I wanted to share my issue. While attempting to run the unit test for my application, I encountered a TypeError. The error message stated: "TypeError: Cannot read properties of undefined (reading 'push')" ...

What is the best way to wrap the countdown numbers with <span> tags?

I have implemented the following countdown script: var clock = document.getElementById("timeleft"), tdy = new Date(1494979200000); countdown.setLabels( '| <span class="time-label">second</span>| <span class="time-label">minute< ...

The method I used to position a triangle at the bottom border of a parent element with relative

https://i.stack.imgur.com/RZjJ9.png I am trying to achieve a centered triangle within a border, but I am facing a challenge due to the parent component being relative. When I remove the relative positioning, I struggle to position the triangle in the cent ...

Revamp the current webpage to display attribute values in textual format

As I peruse a webpage, I notice that there is room for improvement in terms of user-friendliness. The page is filled with a list of movie titles, each accompanied by a link to IMDb. However, the IMDB user rating is only visible when hovering over the titl ...

The bottom of the page displays varying outcomes between Code Snippet (CodePen) and Angular

I had the idea of having my footer cover the entire length of the page and stick to the bottom, adjusting itself if more content is added. However, I encountered an issue where on Codepen everything works perfectly, but on Angular (14), the footer does not ...

Utilizing the Node -r flag within npm scripts on Azure App Service: A step-by-step guide

I need assistance with running a Node site on an Azure App Service. The issue arises when trying to start the server with the specified line in my package.json scripts. "scripts": { ... "serve": "node -r dotenv-a ...

Unable to successfully import an external HTML file that contains a script tag

I am currently experiencing an issue with my index.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8> <title>MyApp</title> <link rel="import" href="./common.html"> </head> <body> ...

The use of JQuery repeating fields can cause disruptions to the Bootstrap layout when removing rows

I have been struggling with a form that contains multiple fields that need to be repetitive. My current code is functional, but I'm encountering an issue where clicking on any remove button other than the first one causes the fields in the row to rear ...

Creating a gap in an HTML document with a 'division' element and cascading style sheets

I am struggling to create a blank space between my divs. Despite trying numerous CSS properties such as margin-top, padding-top, and others from various sources online, I have not been successful. The only way I can add space is by using an excessive amou ...