The Express JS is having trouble serving the static CSS files through the router

Currently, I am encountering this issue in a larger project, so I have created a simplified version to explain it more clearly.

The Tree Structure of my project is outlined below:

demo
|____admin
|         |____admin.js
|____node_modules
|
|____static
|         |____bootstrap.min.css
|         |____headerStyle.min.css
|
|____views
|    |____admin
|    |    |____admin_home.ejs
|    |
|    |____partials
|                 |____admin_header.ejs
|
|____index.js
|____package-lock.json
|____package.json

I appreciate your patience as I will be sharing the code from some key files.

The code in 'index.js' is as follows:

let express = require('express');
let app = express();
let path = require('path');

app.use(express.static(path.join(__dirname, 'static')));
app.set('view engine', 'ejs');
app.get('/',function(req,res)
{
  res.render('./admin/admin_home');
});

let admin = require('./admin/admin.js');
app.use('/admin',admin);

app.listen(9000,function(){
  console.log('listening to port : 9000');
});

The code in 'admin/admin.js' is as shown below:

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

router.get('/',function(req,res)
{
  res.render('./admin/admin_home');
});

router.get('/adminhome',function(req,res)
{
  res.render('./admin/admin_home');
});

module.exports = router;

The code in 'views/admin/admin.ejs' is displayed here:

<%- include('../partials/admin_header.ejs')  %>

<h1>Admin Home</h1>

I am facing an issue with ExpressJS static file serving.

For the following URLs, webpages render with all the CSS styles applied:

http://localhost:9000
http://localhost:9000/admin

They are served from these paths:

http://localhost:9000/bootstrap.min.css

and

http://localhost:9000/headerStyle.css

However, for the URL below, the webpage is rendered with plain HTML without the CSS styles being served:

http://localhost:9000/admin/adminhome

The error message states:

Failed to load the resources: the server responded with 404

The CSS files are served from these paths:

http://localhost:9000/admin/bootstrap.min.css

and

http://localhost:9000/admin/headerStyle.css

The 'Link' tags in 'vies/partials/admin_header.ejs' appear as:

<link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="headerStyle.css">

The module versions utilized are:

ejs:^2.5.7
express:^4.16.2
path:^0.12.7

My NodeJS version is v8.5.0.

Please assist me in resolving this issue. Thank you!

Answer №1

Roland Starke mentioned that the hrefs of the styles were set relative to the particular URL being visited. To convert them to absolute URLs, all you need to do is add a forward slash like this:

href="/bootstrap.min.css"

Answer №2

Make sure to include the following line in your index.js file:

app.set('views', path.join(__dirname, 'views'));

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

Ways to align page title text at the center of the banner image without using flexbox or grid layout?

Seeking advice on how to vertically center the banner text in the middle of the banner image for a CSS-only psd conversion project. Any ideas on achieving this goal without utilizing flexbox or grid? header { background-image: url(../assets/main-ban ...

What are the steps for creating a Post, Put, or Delete request before fetching with a Get method?

Currently, I am faced with a challenge while using a websocket server to access data from an ExpressJS API. Whenever I perform a fetch operation that updates the database (Postgres) followed by a GET request, the new record is not being included in the res ...

Uploading the file from busboy to Firebase storage

Currently, I am utilizing busboy in node to successfully upload a file to firebase storage. However, upon sending the post request with a file attached, an error message is displayed: { "e": { "code_": "storage/invalid-argument", "mess ...

What is the process for transforming a string into a Cairo felt (field element)?

In order to work with Cairo, all data must be represented as a felt. Learn more here Is there a way to convert a string into a felt using JavaScript? ...

Issues with displaying images have been encountered with the Chessboardjs NPM package

Currently, I am attempting to utilize the https://www.npmjs.com/package/chessboardjs package in conjunction with meteor 1.13. Despite developing a simple react component to display the board, the images are not rendering as expected. Below is the code for ...

What is the process for creating a local repository for Node.js npm?

When it comes to the building process in node js, there are a few goals that need to be called: Begin by calling npm install, which creates a folder called node_modules and places all dependencies from package.json into it. [for UI development] Execute a ...

Place the text below the adaptable div

Could anyone offer guidance on how to properly align text underneath responsive images within divs? The issue I'm facing is that the divs adjust smoothly based on the viewport size, but the text below them doesn't stay centered as intended. Whi ...

What could be causing my Flutter app to fail to connect to my local Node.js server?

Currently, I am learning about nodejs and I have a goal to establish real-time communication between my flutter app and nodejs server, both operating locally. Below is the content of my socket.js file where I am utilizing express and socket io. (I will us ...

"Encountering issues with connecting to the Node.js API hosted on localhost:5000 from the

I have managed to deploy my React app on a digitalocean droplet along with MongoDB integration. The server is configured with Node.js, nginx, and pm2, and everything is running smoothly. You can visit my site here: www.xdomain.ml However, I am facing an i ...

Unexpected interactions between Socket.io and React using hooks

Currently, I am delving into the world of Socket.io with React utilizing Hooks. My goal is to create a timer that starts upon pressing the start button, and then every second, send the current time in the state to the server using socket.io. The server co ...

I am facing an issue where Postman is not displaying the HTML pages I create in Express

I am facing an issue with linking my HTML page to my express app and trying to view the content through Postman. However, Postman is only displaying a blank page instead of showing my HTML content. Surprisingly, when I test using res.get("this is an exampl ...

I'm diving into the world of Angular and Node.js and looking to transform XML into JSON. I'm torn between using the xmltojson and xml2json npm packages

I'm curious about a couple of things: 1. Why are there two different options for the same thing? 2. How do we decide which one to choose, and what criteria should we use? My application is built using Ionic 2, Angular, and Android. Can you please ...

The error message in Next.js keeps popping up because it detects that I am using a non-standard NODE_ENV, even though I have already

Upon deploying my Next.js project within a Docker linux container, an issue arises during startup where Next.js alerts that You are using a non-standard "NODE_ENV" value in your environment. Even though the NODE_ENV is configured as development, ...

CSS causing black bars to appear when image is moved

I recently started working with HTML/CSS and JS, but I've encountered a small issue. I'm using the bootstrap carousel and it's functioning well, but when I try to move the image higher up, black bars appear at the bottom as if my images are ...

Activate $digest when a variable is modified by a node.js function

I am currently working on developing an application using node-webkit and AngularJS. Everything was going smoothly until I tried to make Angular watch over a "legacy variable" using the method outlined in this answer, which led to an Error: [$rootScope:inp ...

Yarn installation halted due to an unexpected end of file

Encountering an issue with npm/yarn. Our private npm registry is hosted on a VM using Verdaccio to manage our packages. Whenever we install external packages for the first time, they are redirected to registry.npmjs.org through http://localhost:4873 and th ...

Tips on how to send data to a Promise?

After sending data to my app via a POST request, I write it to a file and share it with other instances using PUT. My goal is to receive the status of each stream (file and PUT requests) upon completion of the process. The array putResults belongs to the ...

What could be preventing the webpack dev server from launching my express server?

Currently working on a straightforward web application using express and react. The front-end React bundle is being served via the express server. Everything runs smoothly with my start script, which builds the front-end code and launches the express serv ...

Stream events are not being recorded for reading an empty file within a timeout period

I'm currently developing code that involves reading from a file and incorporating timeout functionality. I've encountered some issues specifically related to empty files. In the absence of a timeout, the output would typically display something ...

Discrepancies in display grid rendering in Firefox versus Chrome

I'm experimenting with creating a master-detail view by showcasing two CSS tables (display:table) side by side. To organize the layout, I've implemented CSS Grid. The master panel typically contains 1 to 10 rows while the detail content can exce ...