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.