0
votes

I have created a site, that have root, help and 404 paths and pages in hbs format. The issue is that when I run localhost:3000/wrong it shows the site correctly but when I run localhost:3000/help/wrong the css part doesn't get applied to that 404 page as it should, because there is not route /help/wrong.
I run the code using node app.js or nodemon app.js.

Folder Structure:

  • public
    • css
      • styles.css
  • templates
    • partials
      • animal.hbs
      • info.hbs
    • views
      • 404.hbs
      • help.hbs
      • index.hbs
  • app.js
  • package.json
  • package-lock.json

package.json

"dependencies": {
 "express": "^4.17.1",
 "hbs": "^4.1.1"
},
"devDependencies": {
 "nodemon": "^2.0.7"
}

app.js

const express = require("express");
const hbs = require("hbs");

const app = express();

app.set('view engine', 'hbs');
app.set('views', './templates/views');
hbs.registerPartials('./templates/partials');
app.use(express.static('./public'));

const animal = 'Tiger';
app.get('', (request, response, next) => {
    response.render('index', {
        title: 'Root',
        animal
    });
})

app.get('/help', (req, res) => {
    res.render('help', {
        title: 'Help',
        animal
    })
})

app.get('/help/*', (req, res) => {
    res.render('404', {
        title: '404',
        animal,
        error: 'Help Page Not Found!'
    })
})

app.get('*', (req, res) => {
    res.render('404', {
        title: '404',
        animal,
        error: 'Page Not Found!'
    })
})

app.listen(3000, () => {
    console.log("Server is on port 3000");
})

index.hbs

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Root</title>
    <link rel="stylesheet" href="css/styles.css">
</head>
<body>
    {{>info}}
    {{>animal}}  
</body>
</html>

help.hbs

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Help</title>
    <link rel="stylesheet" href="css/styles.css">
</head>
<body>
    {{>info}}
    {{>animal}}
</body>
</html>

404.hbs

<!DOCTYPE html>
<html lang="en">
<head>
    <title>404</title>
    <link rel="stylesheet" href="css/styles.css">
</head>
<body>
    {{>info}}
    {{error}}
    {{>animal}}
</body>
</html>

animal.hbs

<p>Animal is {{animal}}</p>

info.hbs

<h1>{{title}}</h1>
<a href="/">Root</a>
<a href="/help">Help</a>

styles.css

body {
    background-color: teal;
}

I have tried explaining the question as best as possible. Please do comment if anything is not clear. Thank you so much.

1
The problem is the path to your CSS file. You want it to be relative to the site root, so it should start with a slash, as in <link rel="stylesheet" href="/css/styles.css">. See: stackoverflow.com/questions/62163971/… and stackoverflow.com/a/61741846/3397771 - 76484
@76484 Thank you so much. I really didn't knew about this. - Leprachon

1 Answers

0
votes
app.get('/help*', (req, res) => {
    res.render('404', {
        title: '404',
        animal,
        error: 'Help Page Not Found!'
    })
})

Does removing the / before the * do the trick?