In developing my website I ran across an issue with the way that my static CSS, JS, and image files are being loaded to my site. Once I navigate past the .index file or any route tree, my static directory misloads and the route index suddenly is added to the static file directory path.
I have written a yelpcamp app that I am modeling this app off of that works fine as I have it written, but this for some reason is throwing this specific error I can not find any resources to help correct.
Main app.js file that has all declarations and static file load
// REQUIREMENTS
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
methodOverride = require("method-override"),
nodemailer = require("nodemailer"),
expressSanitizer= require("express-sanitizer"),
// MODELS
blog = require("./models/blog"),
// ROUTES LOCATIONS
indexRoutes = require("./routes/index"),
blogRoutes = require("./routes/blog"),
contactRoutes = require("./routes/contact");
// SETUP
mongoose.connect("mongodb://localhost/*ChangedForPrivacy*");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(methodOverride("_method"));
// ROUTE INDEX
app.use("/", indexRoutes);
app.use("/contact", contactRoutes);
app.use("/blog", blogRoutes);
This is the blog.js file in my routes folder where I noticed the static files loading correctly
// REQUIREMENTS
var express = require("express"),
Posts = require("../models/blog"),
router = express.Router();
// INDEX- SHOW ALL Posts
router.get("/", function(req,res){
// find all POSTS
Posts.find({}, function(err, allPosts){
if(err){
console.log(err);
} else{
// this is index because lots of paths are derived from it (landing pages are separate entities)
res.render("blog/home",{posts: allPosts});
}
});
});
// NEW (FORM PAGE)
router.get('/new', function (req,res){
res.render("blog/newpost");
})
// CREATE (POST TO PAGE)
// EDIT (PUT TO PAGE)
// DELETE
// EXPORT TO ROUTER
module.exports = router;
the /blog/home page loads the static CSS, JS perfectly but once you get to /blog/newpost it changes the path of the static files to now include the /blog in it. I would expect if the first app.get in the route structure would work they would all follow, but I am at a loss why it keeps adding the additional route directory.
I found my mistake in my partials/header.ejs file. I left out the "/"before the root of my static CSS/JS files so the router followed its path and added the route as it correctly should have.