Struggling to locate the correct path for the CSS file in Express and Handlebars

As part of a student exercise, I am attempting to access an API containing information about presidents and style them using CSS. However, I am facing issues with linking the style.css file.

I have tried various methods to change the path and public path in the server.js file, as well as the line

app.use(express.static(path.join(__dirname, 'public')));
, but so far nothing has worked. I could use some assistance from someone more experienced in Express and Handlebars. Thank you!

Here is the file structure:

/public
 . css
  .. styles.css
/views
 . layout.hbs
 . presidents.hbs
/index.html
/server.js

server.js

const fetch = require('node-fetch');
const express = require('express');
const app = express();
const path = require('path');
const publicPath = path.join(__dirname, '../public');

app.set('view engine', 'hbs');

async function fetchAndParseData() {
  const r = await fetch('https://api.sampleapis.com/presidents/presidents');
  const data = await r.json();
  return data;
}

app.use(express.static(path.join(__dirname, 'public')));

// The method `.use` sets up middleware for the Express application
app.use(express.json());
// this parses requests that may use a different content type
app.use(express.urlencoded({ extended: true }));

app.get('/presidents', async (req, res) => {
  const data = await fetchAndParseData();
  res.render('presidents', { data });
});

app.get('/', (req, res) => {
  res.send('<h1>Presidents Site</h1>');
});

app.listen(4001, () => {
  console.log('SomeApp HTML');
});

layout.hbs

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Express HTML Site</title>
</head>
<body>
  {{{body}}}
</body>
</html>

presidents.hbs

<h1>All our presidents</h1>
{{#each data}}

<section id="presidents">
<figure class="president">
  <img src={{this.photo}} alt={{this.name}}/>
  <caption>{{this.name}}</caption>
  </figure>
{{/each}}
</section>

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="/css/styles.css" />
    <title>Document</title>
  </head>
  <body></body>
</html>

Answer №1

Even though I can't physically see how you've implemented the handlebars package in your server.js file, I'm assuming you have simply left it out since you're only asking for help with the CSS.

Both of these methods should work equally well:

app.use(express.static(path.join(__dirname, 'public')));

or

app.use(express.static(__dirname + '/public'));

However, don't forget to include the stylesheet link in your layout.hbs file like this:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <link rel="stylesheet" href="/css/styles.css">
      <title>Express HTML Site</title>
   </head>
   <body>
     {{{body}}}
   </body>
</html>

Right now, it seems like you're only including them in your index.html file.

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

The error message from the mongoose plugin is indicating a problem: it seems that the Schema for the model "Appointment" has not been properly registered

I need help troubleshooting a mongoose error that is being thrown. throw new mongoose.Error.MissingSchemaError(name); ^ MissingSchemaError: Schema hasn't been registered for model "Appointment". Use mongoose.model(name, schema) I have double-c ...

Shake up your background with a random twist

Seeking assistance with customizing the Aerial template from HTML5UP. I am interested in selecting a scrolling background randomly from a pool of images. Can someone guide me on how to achieve this? Presently, the background is defined within a code block ...

Utilizing window.matchMedia in Javascript to retain user selections during page transitions

I am encountering difficulties with the prefers-color-scheme feature and the logic I am attempting to implement. Specifically, I have a toggle on my website that allows users to override their preferred color scheme (black or light mode). However, I am fac ...

Utilize CSS block display for ::before and ::after pseudo elements within a div container

I have a CSS file that contains the following code snippet: .loader { width: 250px; height: 50px; line-height: 50px; text-align: center; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-fam ...

When using npm link, it searches for the module in the src directory rather than the dist directory

In my experience with Angular CLI Builder, I have implemented a custom builder to extend the asset configuration in angular.json for libraries that have their own assets. To manage my workspace, I utilized nrwl. I created an Angular CLI builder library an ...

Sending images from a C# application to a NodeJS Express server using the PUT method through HttpWebRequest

I have a C# code snippet that is successfully working with another NodeJS Express application, the source code of which I do not have access to. However, I want to keep this code unchanged. string filetoupload = @"D:\testvideo.mp4"; HttpWeb ...

What is an alternative method to retrieve form data without relying on bodyParser?

When it comes to accessing posted form data without using bodyParser, what alternatives are available? How exactly does bodyParser grant access to the data in req.body? Additionally, I am curious about the inner workings of this process on a deeper level. ...

Pagination functionality in TablePress allows for improved organization and

Currently, I am utilizing the TablePress plugin on my WordPress website and I am aiming to achieve a pagination layout similar to this illustration: . How can I modify the pagination to display the text 'page 1 of X' instead of 'previous&apo ...

What is the best way to horizontally align an element within a Material UI Grid item?

How do I align elements in the center of a Material UI Grid item? Check out this code snippet from my React project: <Grid container> <Grid item xs={4}> // Other content goes here </Grid> <Grid item xs={4}> // How can ...

Best approach to disentangle nowjs code from your application (written in coffee/js)

Is it advisable to separate my nowjs code from the main app file? everyone = require("now").initialize app, { socketio: { transports: ['xhr-polling', 'jsonp-polling'] } } everyone.now.distribute_event = (event, day) -> everyone.n ...

Error message: IndexError: list index out of range while attempting to trigger a click event using selenium

There are a total of 41 category checkboxes on the page, with only 12 initially visible while the rest are hidden. To reveal the hidden checkboxes, one must click on "show more." This simple code accomplishes that: [step 1] Loop through all checkboxes >> ...

The HTTP GET request is failing to trigger

I'm currently working on building a basic messageboard using MongoDB, Angular, NODE.js and Express. Oddly enough, everything works fine the first time I call getMessages(). But when I try to call getMessages() after posting a message with postMessage ...

Encountering issues during the installation process of Yarn

I am facing an issue while trying to set up yarn on a new machine. When I input brew install yarn in the command line, I receive the following output: touch: /usr/local/Homebrew/.git/FETCH_HEAD: Permission denied touch: /usr/local/Homebrew/Library/Taps/ho ...

Error occurs when attempting to write to a Node stream after it has already

I'm experimenting with streaming to upload and download files. Here is a simple file download route that unzips my compressed file and sends it via stream: app.get('/file', (req, res) => { fs.createReadStream('./upload/compres ...

Is there a way to remove the scrollbar from the menu created with react-burger-menu?

How can I remove the scroll bar from the menu created with react-burger-menu? Despite trying various CSS properties adjustments, I have not been able to achieve the desired effect. Here is an image of the open menu and the corresponding CSS: (https://i.st ...

PHP Retrieve Current Time with AM/PM Display

Can anyone help me figure out how to use PHP to get the current time along with AM/PM indication? The code I have doesn't seem to be working correctly. Here is the code snippet that I am currently using: $format1 = date("G"); // this should give the ...

Leverage elements from nearby npm repository when building an Angular 2 application

After developing a generic chart component using d3 and Angular 2, I decided to share it by publishing it in a local npm repository. This way, anyone can easily incorporate the chart component into their Angular project by simply running the npm install my ...

Problem with IE off-canvas scrolling

Currently, I am facing an issue with the scrolling functionality of an off-canvas sidebar on my Joomla 3 website. It seems to be working fine in Chrome and Firefox, but when it comes to Internet Explorer, the visible scroll bar refuses to move when attempt ...

Experiencing problems with uploading a file with multer

When attempting to upload a file using multer, I encountered the following issue in my code: var multer = require('multer'); var upload = multer({ dest: 'uploads/' }); app.post("/upload",upload.single('image' ...

Is there a way to exclusively display the current user in an HBS template when printing?

I am trying to display the username of the currently logged-in user by retrieving it from my database. The schema for the username property in my model is as follows: { type: String, required: true } index.js: const users = require('../model/ ...