When accessing localhost/about/{randomtext} in Node.js, the CSS file fails to load on the 404 error page

My issue is that the css file does not apply to localhost/about/{anyrandomtext} but it applies to localhost/{anyrandomtext}

I attempted to fix this using the following code snippets, but it did not work :

app.get('/about/*', (req, res) => {
    res.render('404')
})
app.get('*', (req, res) => {
    res.render('404')
})

I utilized

app.use('/public', express.static(staticFilePath))
based on guidance from Express.js StaticPath problem | CSS not being applied on one Page while HBS not getting loaded on other Page, which resolved the CSS applying issue on all pages except for the 404 error page. Here is my file structure:

https://i.sstatic.net/Uuefu.png

header.hbs

**<link rel="stylesheet" href="public/css/styles.css">**
<title>Weather</title>

404.hbs

<!DOCTYPE html>
<html lang="en">

<head>
    {{> header}}
</head>

<body>

    <div class="container error_page">
        <img src="../../public/images/404error.png" alt="">
        <h1>Page could not be Found</h1>
        <button type="button" class="btn">Go to Home</button>

    </div>

</body>

</html>

Please review the provided code and offer assistance. Thank you.

const express = require('express')
const hbs = require('hbs')
const path = require('path')
const port = process.env.PORT || 8000
const app = express()

const staticFilePath = path.join(__dirname, '../public')
const viewsFilePath = path.join(__dirname, '../templates/views')
const partialPath = path.join(__dirname, '../templates/partials')

hbs.registerPartials(path.join(partialPath))
app.set('view engine', 'hbs')
app.set('views', viewsFilePath)
app.use('/public', express.static(staticFilePath))

app.get('/', (req, res) => {
    res.render('index')
})
app.get('/about', (req, res) => {
    res.render('about')
})
app.get('/weather', (req, res) => {
    res.render('weather')
})

app.get('*', (req, res) => {
    res.render('404')
})

app.listen(port, () => {
    console.log(`Successfully connected at port ${port}`);
})

Answer №1

Try using

app.use(express.static(staticFilePath))
in place of
app.use('public', express.static(staticFilePath))

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

Paragraph opacity adjustments can alter both the text and background opacities

Is there a way to change the opacity of only the background of a paragraph without affecting the text? When I try to adjust the opacity, it changes both the text and the background. How can I resolve this issue? HTML <div id="opener"> <p id="in ...

How can I implement callback functions in joi validation?

Exploring the World of Coding I came across a code snippet online that caught my attention, but upon closer inspection, I realized it used Hapi/Joi which is now considered outdated. My question is how can I modify this code to work with Joi? app.post(&apo ...

Analysis of npm script execution time and performance metrics

Can the performance of npm scripts be measured in a similar way to how time-grunt operates? I'm transitioning some critical build tasks to use npm instead of Grunt because creating my own build script offers more flexibility than relying on certain G ...

"Is an Ionic Top Navigation Bar the best choice for your

Creating an Ionic Top Navigation Bar Greetings! I am facing some challenges while trying to implement a Top Navigation Bar in my Ionic Project. Despite the lack of documentation on this specific topic, I am struggling to make it work properly. Your as ...

Employing an odd/even toggle for assigning class names

I need each this.state.title to be aligned based on a different classname. I attempted using css flex boxes/nth-of-type/nth-child, but it didn't work well with React. I'm utilizing this.state to access my objects. My failed strategy render: f ...

Node.js with ejs supports the inclusion of partials, but sometimes struggles to locate the variable that has been defined in the partial file

This is the code that should be included in the main ejs file: <% const IDP_URL = "http://idp.com:8082"; const SP_ID = "testing"; const SP_SECRET = "XRRpYIoMtaJC8hFLfUN7Bw=="; const TOKEN_VERIFY_FAIL_URL ="/exsignon/sso/token_verify_fail.ejs"; const L ...

Next.js: Importing from a new endpoint triggers the code execution once more

Here is a simplified example I created for this specific question. Imagine I want to maintain a server-side state. components/dummy.ts console.log('initialize array') let number: number = 0 const incrementValue: () => number = () => numbe ...

Mismatch in Angular context

I am facing an issue with my Angular server not responding to http://localhost:8449/spreadsheet-upload. I have set a base href='/spreadsheet-upload" and routes that start with that. My goal is to prefix all references to my server with the hostna ...

Update the content of the widget

Currently, I am utilizing the following script to display NBA standings: <script type="text/javascript" src="https://widgets.sports-reference.com/wg.fcgi?script=bbr_standings&amp;params=bbr_standings_conf:E,bbr_standings_css:1&amp"></sc ...

The previous button on Owl Carousel seems to be malfunctioning after navigating from a different page

In my case, I have two distinct pages: let's call them the first and second pages. On the first page, I utilize an owl carousel slider with a tag that links to a specific slide on the second page's owl carousel slider using an ID. Meanwhile, on ...

Achieve full height in Grid component of material UI by eliminating margins

In this codesandbox example, I have successfully set the grid container height to full using 100vh. However, there is an issue with a margin of 8px being added by the user agent to the body element, and I'm struggling to find a solution to remove it. ...

What is the process of setting the maximum number of listeners with "emitter.setMaxListeners()"?

Whenever I make a GET request to a specific URI using the 'request' module in node.js; var options = {uri:"aURI", headers:headerData}; request.get(options, function (error, response, body) { } An error message pops up: [Error: Exceeded maxRedi ...

Encountering the error message `TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"` with `ts-node` when the type is specified as module

After configuring absolute paths in my Express project and changing the type to module for using import, I encountered an error: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" Below is the content of my tsconfig.json { &q ...

Encountering an issue with npm installation process: error

I've encountered an issue while trying to install a project from GitHub. After following the installation instructions and running npm install in the project directory, I'm receiving the error message shown below: root@server:/var/www/nomp# npm ...

I am encountering a 500 error in my command prompt while attempting to include a new page in my project

Currently, I am in the process of setting up an addpost page and encountering an issue where I keep receiving a "GET /posts/add 500 4.339 ms - 204" message on my command prompt. If you need to access the full code, feel free to visit: https://github.com/v ...

CSS Transform animation does not work when a class is added programmatically, although it functions properly when toggling the class in Chrome

Attempting to create an animation for the transform of a div. Below is the code with transition and transform properties in Safari: #mydiv{ transition: all 2.3s cubic-bezier(1, 0, 0, 1); transform: scale(0.5); background:white; padding:30 ...

How can a controller in AngularJS detect when the back button of the browser is pressed

I've created a browser trivia game where authenticated players can select a game type, triggering a socket.io event in my Node.js server. The view then transitions to a "Searching for game" screen with a loading icon as the server waits for enough pla ...

Error encountered: NodeJS and Google Cloud Platform PubSub - Issue with PubSub constructor in Object anonymous

Currently, I'm working my way through a tutorial found at and encountering some challenges. In my server.js file, the following code snippet is causing me trouble:- const express = require('express'); const app = express(); const path = r ...

React struggling to retrieve the initial value from localStorage

Hello everyone! I am currently working on a MERN app and have been exploring how to implement JWT token authentication. Everything seems to be working fine, but I encountered a small issue on the frontend. After a user logs in, the token is successfully se ...

Is a one-way synchronization better than a two-way synchronization for Docker Volumes?

For my Full Stack Javascript project, I am utilizing Docker Compose in my local development environment. Here is a snippet of my Docker Compose file: version: "3.5" services: frontend: build: context: ./frontend/ dockerfile: dev.Dockerfi ...