Express router is not functioning properly with the static CSS file

My current project involves using Express to create a login application, with EJS as the chosen template engine. The file structure of the application is as follows:

package.json
server.js
routes
   index.js
   users.js
views
   layouts.ejs
   login.ejs
   register.ejs
   welcome.ejs
public
   css
      bitnami.css

The 'bitnami.css' file contains CSS code downloaded from Bootswatch.

In 'server.js', the following code is implemented:

const express = require('express');
const app = express();
const PORT = process.env.PORT;
const expressLayouts = require('express-ejs-layouts');
const path = require('path');
global.appRoot = path.resolve(__dirname);
console.log(path.join(global.appRoot,"public"));

//EJS
app.use(expressLayouts);
app.set('view engine','ejs');
//set static path
app.use(express.static(path.join(global.appRoot,"public")));
//Routes
app.use('/',require('./routes/index'));
app.use('/users',require('./routes/users'));

app.listen(PORT,()=>{
    console.log(`server running at ${PORT}`);
})

'index.js' includes:

const express = require('express');
router = express.Router();

router.get('/',(req,res)=>{
    res.render('welcome',{layout : 'layouts'});
})

In 'users.js', the code is as follows:

const express = require('express');
router = express.Router();
router.get('/login',(req,res)=>{
    res.render('login',{layout : 'layouts'});
})
router.get('/register',(req,res)=>{
    res.render('register',{layout : 'layouts'});
})

module.exports = router;

module.exports = router;

The 'layouts.ejs' file contains the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>BNI EVENT</title>
    <link rel="stylesheet" href="css/bitnami.css">
    <script src="https://kit.fontawesome.com/9c59f82571.js" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container">
        <%- body %>

    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
    </script>
</body>

</html>

When loading the CSS file from a CDN or using a static middleware for routes with paths other than '/', such as '/users', the CSS file works correctly. However, I am seeking a less redundant solution to this issue.

Adding the following code to 'users.js' ensures the CSS file functions properly:

const express = require('express');
router = express.Router();
const path = require('path');
// setting the static middleware for this route 
router.use(express.static(path.join(global.appRoot,"public")));
router.get('/login',(req,res)=>{
    res.render('login',{layout : 'layouts'});
})
router.get('/register',(req,res)=>{
    res.render('register',{layout : 'layouts'});
})

module.exports = router;

Answer №1

This issue seems to be quite straightforward

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>BNI EVENT</title>
    <!-- custom change here -->
    <link rel="stylesheet" href="/css/bitnami.css">
    <script src="https://kit.fontawesome.com/9c59f82571.js" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container">
        <%- body %>

    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="44542b34343427306c283102773c373637">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>

</html>

In my layout file, I had been using css/bitnami.css which caused some routing issues. For instance, when trying to access url.com/add, the browser would look for the file in add/css/bitnami.css. To avoid this, I had to specify /css/bitnami.css to direct the browser to the main directory's css folder.

Updated code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>BNI EVENT</title>
    <!-- change is here -->
    <link rel="stylesheet" href="/css/bitnami.css">
    <script src="https://kit.fontawesome.com/9c59f82571.js" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container">
        <%- body %>

    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="37372b34343427303c3c3e3b3b313635257c303e">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>

</html>

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

Add formatting to a particular element without affecting elements within another element

Consider the following scenario: <input type='text' /> <br /> <iframe> <input type='text'> </iframe> With the style defined as: input[type='text'] { border: 1px solid black; } If you w ...

Is it possible to utilize Node.js cluster with a single-core processor?

My node.js application handles multiple client requests simultaneously. When running on a server with a multi-core processor, leveraging Node.js cluster can optimize performance by creating multiple workers to process tasks in parallel and distribute the l ...

What is the best way to pass my session token information between various JavaScript files on the server?

Here's the current status of my session tokens on the server: In my server.js file: app.use( session({ secret: "{ ...

Tips for flattening sub-documents within MongoDB

My data collection consists of documents like the following: { "_id" : ObjectId("587c8d0364b6e32706f7edef"), "first_name" : "John", "last_name" : "Doe", "password" : "aasdjsabb12213b21bbcghc1h2", "shift" : "A", "dept" : "Management" "Requests" : [ { ...

Is updating node and npm on Windows really as complicated as it seems?

After spending an excessive amount of time on this issue, I am on the verge of giving up. I am aware that Node can be updated through the official website, but I would prefer to do it via the command line. When attempting npm install npm@latest -g I enc ...

CSS - Ignoring Padding Causes Unexpected White Space to Appear

I am encountering a simple error, and the following address will direct you to where the issue can be seen. Why is certain parts of the header appearing white instead of the light shade of green it is set to be? It should be positioned right at the top un ...

housing the picture within a CSS grid

I am new to working with css grids and I have encountered an issue. The background image I want to use is larger than the size of the grid itself. How can I make the image fit within the grid without exceeding its boundaries? When I attempt to insert the ...

Is there a way to modify the commandlink image when the mouse hovers over it in PrimeFaces?

After implementing this code snippet, my commandlink seemed to vanish into thin air. Upon inspecting it with firebug, I discovered that it was present but had a size of 0 x 0 px. .myNewButton { width: 50px !important; height: 50px !important; background ...

The attribute selector is malfunctioning

Currently, I am attempting to target img tags based on the alt attribute in order to correctly load a background-image on mobile devices. The issue I am encountering is that regardless of the combination of attribute selectors I use, it does not seem to w ...

Despite encountering an error in my terminal, my web application is still functioning properly

My code for the page is showing an error, particularly on the home route where I attempted to link another compose page The error message reads as follows: Server started on port 3000 Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after t at new Node ...

Connect with me on my public IP on Hack.chat

Recently, I came across a fascinating chat application; https://github.com/AndrewBelt/hack.chat I successfully installed it and everything seems to be functioning properly. The server is located at 127.0.0.1:6060 and the client (running via http-server) c ...

Unforeseen outcomes when setting background colors with Anime.js

I've recently started experimenting with Anime.js. I have a piece of code that I'm using to animate a div element with an id of a. anime({ targets: "#a", translateX: 250, color: "#fff", backgroundColor: "hsl(200, 50%, 50%)", ...

Encountering an issue when trying to execute the Yeoman generator

I was in the middle of following a tutorial on mean.js, which can be found at . However, when I ran the command yo meanjs, I encountered the following error: Error: Error: Command failed: C:\Windows\system32\cmd.exe /s /c "git --version" ...

Angular 2: Enhancing Tables

I am looking to create a custom table using Angular 2. Here is the desired layout of the table: https://i.sstatic.net/6Mrtf.png I have a Component that provides me with data export class ResultsComponent implements OnInit { public items: any; ngO ...

Sinon - the ultimate guide to intercepting the save() function in a mongoose schema

Currently, I am in the process of writing unit tests for an API that utilizes MongoDB in conjunction with mongoose for database access. Within my codebase, there exists a model file that defines and exports a mongoose model as shown below: const { Schema, ...

Tips for connecting to a MongoDB database on a separate server

Within a microservice setup, I am managing two distinct services each with its own mongoDB database - Teacher-Service and Student-Service. My current task involves setting up a login feature where upon user submission of an email, I need to simultaneously ...

How to Customize the Drawer Color in Material-UI v5

I'm currently using MUI v5 in my project and I am encountering some challenges while attempting to style a Drawer component with a black background color. As this update is relatively new, I have not been able to find much information on customizing t ...

Retrieve the file ID once the resumable upload to Google Drive has been successfully completed

Currently, I am in the process of integrating the Google Drive API into my application, specifically using the resumable upload approach. However, I am facing a challenge in determining how to obtain the file ID once the upload is complete and included in ...

The scrolling function of the jQuery UI select menu is not working properly on the Android browser

I am currently developing a mobile application that utilizes the jQuery UI select menu. The functionality works well, but I have encountered an issue with certain drop downs being too long to display properly. While my PC shows scrollable floating divs as ...

Resizing cell height in an HTML table is not supported by Angular 5

In my angular application, I've implemented a component that represents a basic HTML table. However, I'm facing an issue with reducing the height of cells within the table. It seems like my CSS styling is not affecting the display as desired. He ...