The individual blog pages on my site are not receiving the static files they need to display

I'm facing an issue serving a css file to individual blog posts on my website's blog section.

Here's how it's supposed to work: Visit /blog- you'll see the main blog page, which is functioning fine.

However, when trying to access, for instance, /blog/post1, I encounter this error:

http://localhost:4000/blog/static/css/style.css

I could really use some assistance since I'm fairly new to express and routing files. Thanks in advance.

My folder structure is as follows


    blog
        /node_modules
        /src
            /mock
            /public
                /css
                    style.css
            /templates
                /partials
                    _head.jade
                    _nav.jade
                blog.jade
                index.jade
                layout.jade
                post.jade
            app.js

Here's how it should work: Go to /blog- you get the blog page and everything is good.

But when trying to navigate to, say, /blog/post1, I encounter the error

http://localhost:4000/blog/static/css/style.css

This is what my respective files look like, maybe there's something missing:

app.js

"use strict";

var express = require("express"),
    posts = require("./mock/posts.json");

var postsLists = Object.keys(posts).map(function(value){
    return posts[value]
    });

var app = express();

app.use("/static", express.static(__dirname + "/public"))

app.set("view engine", "jade");
app.set("views", __dirname + "/templates");

app.get("/", function(req, res){
    res.render("index");
});

app.get("/blog/:title?", function(req, res){
    var title = req.params.title;
    if (title === undefined) {
        res.status(503);
        res.render("blog", {posts: postsLists});
    } else {
    var post = posts[title] || {};
    res.render("post", {post: post} );
    }
});

app.get("/about", function(req, res){
    res.send("<h1>About Page</h1>");
})

app.get("/projects", function(req, res){
    res.send("<h1>Projects Page</h1>")
})

app.listen(4000, function(){
    console.log("Frontend server is running on port 4000.")
});

_head.jade

head
meta(charset="UTF-8")
link(rel="stylesheet", href="static/css/style.css")

layout.jade

doctype html
html(lang="en")
include ./partials/_head.jade
body
block content

blog.jade

extends ./layout

block content
    section(id="postHolder")
        for post in posts
            div.post
                h2 #{post.title}
                p #{post.body}
                a(href="/blog/" + post.title)
                    button Read More

post.jade

extends ./layout.jade

block content
    section
            div.post
                h2 #{post.title}
                p #{post.body}
                p This is the actual post page itself.

Answer №1

Perhaps following these steps will lead you to success -

start
  label(lang="en")
  link(type="text/css", href="/styles/custom.css")

Answer №2

Let me point out something in my _head.jade file that needs your attention:

head
meta(charset="UTF-8")
link(rel="stylesheet", href="/static/css/style.css")

I had to update the reference to make it an absolute path by adding a "/" in front of "static"

Originally, it was static/css/style.css and now it's /static/css/style.css. I'm still learning, so I hope I clarified the concept of an absolute path correctly.

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

Tips for saving an array from the server into a script variable

I'm currently working with the express js framework along with Handlebarsjs as the templating engine. My aim is to pass an array from the router to the view, and then store this array within a script tag. //users is an array res.render('chatRoom ...

At times, the Node.js process.domain may become unexpectedly undefined

Within the context of a Node.js project developed with LoopbackJS, there is a need to store data during each request. To achieve this, the domain feature was utilized: // Pre-processing middleware app.use(function (req, res, next) { // Create an instan ...

Div failing to expand to fit its contents

I'm having trouble getting my info-container div to adjust its height based on its contents. I suspect that the floating div within it might be causing the issue, but I'm not certain. I've included a link to jsfiddle where you can view the C ...

Issue with babel configuration not functioning properly within the project when installed as an npm package

I recently built an npm package and included a babel.config.json file with the following content: { "presets": [ "@babel/preset-env", "@babel/preset-react" ], "plugins": [ "@babel/plugin-syntax ...

Misunderstanding between Typescript and ElasticSearch Node Client

Working with: NodeJS v16.16.0 "@elastic/elasticsearch": "8.7.0", I am tasked with creating a function that can handle various bulk operations in NodeJS using Elasticsearch. The main objective is to ensure that the input for this funct ...

The image showcases interactive hover effects that resemble a button popping up

Welcome to my HTML code showcase: <div class="container"> <a target="_self" href="flower_gallery.htm"> <img data-src="holder.js/180x180" style="height:20%;width:100%;float:left;" ...

Animate linear-gradient using jQuery script

I have been searching for a circular progress bar plugin but haven't found one that suits my needs, so I decided to build my own using pure CSS: http://jsfiddle.net/9RFkw/ While it looks great, there are two issues I am facing: 1.) When at 25% in F ...

Exploring Best Practices for Coding in node.js

Method 1: Constructor and Prototype Objects function Database(url) { this.url = url; } Database.prototype.info = function (callback) { http.get(this.url + '/info', callback); }; Method 2: Closures Approach function Database(url) { ...

Order of operation when running a Node.js application

I've always been curious about this and never have come across a satisfactory answer. Let's explore this scenario: var toEmail = ''; if(j==1) { toEmail="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail= ...

Timing routes in ExpressJS - start a setInterval route and stop it with clearInterval route

I have created a Node.js server using Express.js. On one of the routes, I have implemented an interval using setInterval. However, I now need to find a way to stop this interval if a user navigates to a different route. For example: router.get('/sta ...

Encountered an issue while implementing the post function in the REST API

Every time I attempt to utilize the post function for my express rest API, I encounter errors like the following. events.js:85 throw er; // Unhandled 'error' event ^ error: column "newuser" does not exist at Connection.parseE (/Use ...

What methods are most effective for showcasing Flash messages within Express.js?

I have a Node.js app in the EJS framework and I am new to JavaScript. Could someone please advise me on the correct way to set flash messages in Node.js? Below is my code which is throwing an error: C:\Users\sad\Desktop\Node Applica ...

What is the best way to ensure that the child element of a Material UI TableCell Component occupies the full height of the cell?

I am currently using MUI version 5 to create a table. In this table, there are two columns with cells that contain multiline TextFields. My goal is to have the TextFields completely fill the cell area. However, I am encountering an issue where when I start ...

Design inspired by dot matrix patterns

Is it possible to create a background HTML page filled with a dot matrix designing tool? Can anyone provide guidance on how to achieve this? If I need to use a background-image for this, where can I find the appropriate picture? Thank you to everyone in ...

Animate the Bootstrap carousel from top to bottom instead of the traditional left to right movement

Is there an option available in the bootstrap carousel to animate it from top to bottom and bottom to top, rather than from right to left and left to right? jsFiddle link <div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval=" ...

Is it feasible to define the maximum depth of a tree entity in TypeOrm?

In my project, I am considering utilizing the TreeEntity. Specifically, I need to create a tree structure for comments. However, this will depend on user input. To prevent any potential bugs or issues, I am looking to limit the depth of the tree entity. ...

Exploring Java Programming with HTMLEditorKit

Here is my source code: I am trying to change the font color using only CSS. This is how I am inserting HTML: <span class="tag1">I love <span class="tag2">apple</span></span><span class="tag2"> pie</span> When using ...

Tips for enhancing your HTML email template with borders:

I designed an email template using the email template editor and incorporated nested table tags for each mail element. As I created a table to contain all these elements and attempted to add borders to the tags, I encountered a space between the top and bo ...

Encountering a NPM Error while trying to install packages for a fresh project

Yesterday everything was working perfectly fine with installing packages from a project, but today I encountered an error. I attempted to install packages from another project and it seems to work without any issues. I haven't made any changes from ye ...

Tips for extracting text from nested elements

I have a collection of available job listings stored in my temporary variable. I am interested in extracting specific text from these listings individually. How can I retrieve text from nested classes? In the provided code snippet, I encountered empty lin ...