The loading of CSS styles is inconsistent across all pages in node.js

Currently, I am in the process of building a basic blog from scratch to enhance my knowledge of node.js + express. However, I have encountered a roadblock when attempting to access a nested directory, resulting in the styles not loading. For instance:

app.get('/posts/new', (req, res) => {
  res.render('create')
});

Using this path does not render the styles, but '/posts' works perfectly fine.

Does anyone have any insights into what might be causing this issue? Below is the complete code snippet:

const path = require('path');
const expressEdge = require('express-edge');
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = new express();

mongoose.connect('mongodb://localhost:27017/node-blog', {
    useNewUrlParser: true
})
  .then(() => 'You are now connected to Mongo!')
  .catch(err => console.error('Something went wrong', err))

app.use(express.static('public'));
app.use(expressEdge);
app.set('views', __dirname + '/views');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: true
}));

app.get('/', (req, res) => {
  res.render('index');
});

app.get('/posts/new', (req, res) => {
  res.render('create')
});

app.post('/posts/store', (req, res) => {
  console.log(req.body)
  res.redirect('/')
});
app.listen(4000)

Below is the current directory structure:

└── node-blog
    ├── database
    ├── node_modules
    ├── public
        ├── css
        ├── img
        ├── vendor
        ├── js
    ├── theme
    └── views
        ├── layouts

All necessary styles reside in the public folder, while the template engine files can be found in the views directory.

Answer №1

To efficiently load static assets, you can create a virtual path using the following code snippet:

app.use('/assets', express.static(__dirname + '/public/css'));
This setup assumes that all assets are stored in the 'public' directory, with 'css' being the folder containing your CSS files. To reference these assets in your HTML, use the virtual path in the link tag's href attribute. For example, if you have a template file, include the link tag like this:
<link rel="stylesheet" type="text/css" href="/assets/create.css">
I tested this structure and fixed a bug related to loading CSS files. You can see my solution at https://github.com/ardnahcivar/Node.js-Code-/tree/master/11-17-18.

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

React failing to detect updated state from input fields during initial rendering

Hey there, fellow developers! I'm currently working on a simple client in React to test out some functionalities of my API. While my Node.js knowledge is extensive, my understanding of React, states, and hooks is still a work in progress. The Issue: ...

A pair of buttons each displaying a unique div block

I am facing an issue with my jQuery script. I want to be able to click on one of the previewed text associated with a button and then have the other one close automatically. The desired effect is for the text to slide down using slideDown() and disappear ...

Utilizing Regular Expressions in Express.js Routes

Is there a way to extract a specific value from my URL using Express? For example, my URL structure is as follows: host/:value.schema I need to retrieve the value from this URL. Here's an example: host/horse.schema (In this case, the value wo ...

What is the best way to integrate JavaScript into an Express Handlebars template using partials?

In my current project, I have utilized the following handlebars template (located under views/layouts/main.handlebars): <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>{{title}}</title> ...

Creating dynamic PDFs with automatically adjusting heights in DOMPDF Learn how to make

It seems like this question may not have a straightforward answer, but let's give it a shot. My goal is to collect various information from users on my website and display it in an HTML template file that will later be converted into a PDF. With user ...

Using Knex with a SQL Server for a WHERE IN query typically takes 8-12 seconds to retrieve results. Surprisingly, the raw version of the query returned no results. However, when passing

The database is currently stored in the Azure cloud and is not being utilized in a production environment. It contains 80,000 rows where each UPRN is stored as a VARCHAR(100). In order to validate each UPRN, I am already utilizing JOI. For querying the S ...

Installation Failure: Angular-CLI/Chokidents Partnership Error

Newest Node version is 6.7.0 Encountered an error during installation stating notsup not supported by this operating system Operating System: Windows 10 https://i.sstatic.net/jwge3.png ...

Preventing CSRF Errors when activating API endpoints in Node Express JS by ensuring that bypassing the error message with next() function is ineffective

In this middleware block, I have implemented a mechanism to render a 404 page when an invalid CSRF token is detected. /* * Middleware for rendering 404 page on invalid csrf token */ this.app.use((err: any, req: Request, res: ...

Error in creating the database: Outcome is not defined

I am currently working on developing a basic nodejs program using express and mysql. const express = require('express'); const mysql = require('mysql'); const db = mysql.createConnection({ host : 'localhost', user : ...

Issue caused by overflowing content and resizing the display

I am facing a challenge with my website. Essentially, my webpage has the <html> set to overflow:hidden, with two horizontal navbars, a fixed vertical sidebar on the left, and a central div with the height: 90% property. Edit: The container div now ...

Transform static borders into mesmerizing animations by changing the solid lines to dotted lines using CSS

I've managed to create a circle animation that is working well, but now I'm looking to switch from solid lines to dotted lines. Can anyone provide guidance on how to accomplish this? Here is the current appearance: #loading { width: 50px; ...

Showcasing both text and image side by side

https://i.sstatic.net/zR1G1.png Our current method for displaying text in one line and an image below it is shown below. I attempted to achieve this using position : relative: top: xxpx; bottom: xxpx;, but I believe there may be a more efficient way to c ...

Why isn't the background color being applied to my HTML element?

Hello everyone, I am new to the world of HTML/CSS and this forum. I have a question regarding some code I have been working on. Can anyone help me understand why the background color behind the text is not turning green in the following code snippet? ...

Send a variable to a specific page and locate it within a dropdown menu

I am currently working on an HTML page that displays employee leave details. The page includes a pending leave option with the ability to edit. Users should be able to edit their leave while it is still marked as PENDING. Once the edit button is clicked, t ...

Is session affinity necessary for passport.js when deployed across several node.js instances?

Is session affinity required for passport.js when deployed on multiple Node.js instances? When implementing session affinity, authentication works properly with multiple instances behind a load balancer. Redis is used as the session store. However, without ...

I am in search of a clean and efficient method to modify the class of a link that triggers an HTMX request in Django. Perhaps something like "auto-refresh" or a similar solution would be ideal

I've encountered an issue with HTMX in Django. The page consists of two main components: a list of categories and the content that is displayed when a category is clicked. Initially, everything was working smoothly with standard htmx functionality. H ...

What causes the Netlify Run Time Error to appear during deployment?

"scripts": { "test": "echo "Error: no test specified" && exit 1", "start": "nodemon index.js" } netlify shows 9:32:09 PM: build-image version: 01daab3416c9da7032f1dcdb8b1adffdaf5ccb74 (foc ...

Displaying selected list item while concealing the original

I have a dropdown menu with several options. What I am looking for is to have it so that when we click on the drop down, a list of choices appears. Then, when we select an option from the dropdown, the original selection should be replaced with the one th ...

Issue with custom select functionality on Internet Explorer 9

Having some issues with a select element in IE9. The links that should open the wiki page are not functioning properly only on IE9, and there is also an issue with the hover effect - the icon gets overridden by the background color when hovering over help ...

Retrieving SchemaType using ObjectId in Mongoose

When receiving an objectId of an element from the front end, it could belong to one of two models: Containers Schema or Folders Schema. Is there a method in mongoosejs to determine the schema type from the objectId? ...