webpage unable to load properly if URL has three or more slashes

Viewed 18

If I enters something like "http://127.0.0.1/ab" or "http://127.0.0.1/ab/cd" webpage renders properly. But if I use third slash like "http://127.0.0.1/ab/cd/ef" then resulting page does not renders proper. file structure of my project is:

PROJECT
|__node_modules
|___static
|   |__fav0.png
|   |__layout_static.css
|___views
|   |__error404.pug
|   |__home.pug
|   |__layout.pug
|___app.js
|___package-lock.json
|___package.json

app.js file is:

const express = require("express");
const app = express();
const port = 80;

// Middleware
app.use('/static', express.static('static'));
app.set('view engine', 'pug');

// ENDPOINTS
app.get("/", (req, res) => {
    res.status(200).render('home', {title: 'test | home'});
});
app.get("/home", (req, res) => {
    res.status(200).render('home', {title: 'test | home'});
});
app.get("*", (req, res) => {
    res.status(200).render('error404', {title: '404'});
});

// Listen
app.listen(port, () => {
    console.log(`listening at http://127.0.0.1:${port}`);
});

layout.pug:

html
  head
    title= title
    link(rel="stylesheet", href="../static/layout_static.css")
    link(rel="shortcut icon", href="../static/fav0.png", type="image/x-icon")
    block style 
  body
    header 
      nav 
        h2#web_name TEST WEBSITE
        ul#navbar 
          li 
            a(href="/home").nav_link  Home
          li 
            a(href="#").nav_link  Course
          li 
            a(href="#").nav_link  About 
          li 
            a(href="#").nav_link  Contact
    block main_body

home.pug:

extend layout.pug

block main_body
    p This is text for home

error404.pug:

extend layout.pug

block main_body
    h3 ERROR 404 : Page not Found

Kindly provide a solution so that error404 webpage renders properly no matter how many slashes I use.

1 Answers

You're using relative paths in your layout:

link(rel="stylesheet", href="../static/layout_static.css")
link(rel="shortcut icon", href="../static/fav0.png", type="image/x-icon")

Which means that it will only work on pages whose URL will be correct relative to ../static.

Instead, use absolute paths:

link(rel="stylesheet", href="/static/layout_static.css")
link(rel="shortcut icon", href="/static/fav0.png", type="image/x-icon")
Related