I am having trouble connecting my CSS file to my EJS file

I'm having trouble including my external main.css file in my header.ejs file. I've designated my CSS file as public in my backend Node.js with Express.js server (index.js) using this static code:

app.use(express.static("public"));

Then, I connected the header file to the css file like this:

<link href="/Backend/Capstone Project - Public API/public/styles/main.css" rel="stylesheet">

However, none of the CSS styles from the file are showing on the screen (I attempted changing the background color to blue for testing).

Below are the full code snippets:

main.css:

body {
    margin: auto;
    height: 100vh;
    background-color:  blue;
}

h1 {
    color: aqua;
}

index.js

import express from "express";
import bodyParser from "body-parser";
import axios from "axios";

const app = express();
const port = 3000;
const API_URL = "https://www.thecocktaildb.com/api/json/v1/1/random.php";

// Remaining index.js code here...

app.listen(port, () =>{
    console.log(`Server is running on ${port}`);
});

header.ejs:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    // Remaining header.ejs code here...
    
    <title>The Cocktails Generator</title>
</head>
<body>

index.ejs:

// Modified index.ejs code here...

footer.ejs

<footer>
    Footer
</footer>
</body>
</html>

Answer №1

It appears that your css file is located inside the /public/styles/ folder. Since you have set express to serve static files from the public folder which acts as the root directory for static content, all you need to do is update the stylesheet <link> like this:

<link href="/styles/main.css" rel="stylesheet">

In addition, to ensure compatibility with future updates in your app, I noticed that you are creating a __dirname function based on the commented out code. To integrate this with express.static, you can implement it as follows:

import * as path from 'path';
import * as url from 'url';
const __filename = url.fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

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

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

How to use Selenium WebDriver in Python to upload a file using a hidden input field

Html: <div id="js-cert-file" class="form-group"> <button id="js-ob-browse-n-upload" class="btn btn-ob browse-and-upload-onboarding-ssl-button" style=""> BROWSE & UPLOAD </button> <input id="js-cert-file" class="hidden btn btn-ob" ...

What is the best practice for storing API key references and env files within a Node.js application?

What is the proper way to handle sensitive information like api keys and mongo URL in my app.js file? Should I create a separate configuration file, such as config.js, export it as a module, then require it in my app.js file? How can I ensure that when t ...

Exploring Node.js: Deciphering the meaning behind this notation

Recently, I inherited a project from another developer which utilizes the common MEAN stack with server.js as the main entry point. Within server.js, there is a module that includes: var express = require('express'); var app = express(); v ...

Customizing the appearance of the 'Submit' button compared to the <a href=""></a> button using CSS

I am experiencing some issues. Even though the CSS code for these two buttons is exactly the same, their appearance is different. I am unable to make the :hover or :active effects work either. My goal is to have the left 'input type="submit' but ...

Utilizing Multiple Select Options and CSS Float Styling in Mozilla Firefox

I have been attempting to customize the CSS of a multiple select element. While I am satisfied with how it looks on Chrome, I am facing issues getting it to work correctly on Mozilla Firefox. $('option').mousedown(function(e) { ...

Is there a simple way to create a row of triangle-shaped divs using Bootstrap, similar to the design shown

Is it possible to have a white section and background image in the same row? I am aiming for a layout similar to the example shown https://i.stack.imgur.com/J0S2t.jpg ...

Prevent text wrapping and clear floats in a clean and hack-free way

I am currently in the process of compiling a collection of blurbs accompanied by images that can be easily integrated into any section of our website. My goal is to ensure that these blurbs are versatile, free from rigid width specifications, and compatibl ...

Passing backend variables/data to AngularJS in Express JS

As a newcomer to express js, I appreciate your patience with me. I've been diving into "MEAN Web Development" by Amos Q. Haviv and finding it to be an excellent read. However, there's one part that's leaving me puzzled. It seems that in or ...

Arranging cards in a stack using VueJS

I am currently working with a small vue snippet. Originally, I had v-for and v-if conditions in the snippet, but due to issues reading the array, it is now hardcoded. The current setup produces three cards stacked on top of each other. I am exploring opti ...

Modify certain attributes in MongoDB using Mongoose

I am working on creating a basic restful API and I'm facing challenges with updating specific fields in my mongodb using mongoose. Here is the Schema I am using: Sound = new Schema({ "title" : String, "url" : String, "time" : ...

What are the steps to address unhandled promise rejections?

Issue: UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token o in JSON at position 1 Currently working on a MERN stack application. The signup form is in the Frontend, and below is the POST method for it. const onSignUp = async (e) => { ...

Adjust the color of the paper in Material-UI

I'm in the process of creating a React project using the material-ui library. Currently, I am facing an issue with customizing the drawer component's background color. After some research, I learned that modifying the paper attribute of the drawe ...

Strategies for implementing a minimum height for grid-template-column containers

Here's an issue I'm facing: when the first container has content, the other two containers without content end up being the same height as the first one: Check out this JSFiddle link for reference .grid { padding: 5 ...

What are some recommended techniques for retrieving data following a post request in a Node.js environment?

I have a form in Node where I can input user information. After submitting the form, a post request is triggered to add the user to the database. How can I efficiently fetch the data to display a new list of users on the user list? Should I include a get ...

Is there a need to increase the version when making changes to the npm package's

Is it necessary to update the version in package.json and re-publish after making changes to the readme of an npm package I manage? Or is there a different method for updating the readme without incrementing the version? ...

Proper method for incorporating a single database pool across an Express application

Disclaimer: This issue pertains to singleton objects in Node.js and not DB pools. While developing an Express.js application with the mysqljs node module for DB connections, I am interested in creating a single pool object that can be reused across differ ...

Layering elements using the z-index property in Internet Explorer 7,

Issue with text placement in a dialog div only occurring in IE 7. To see the problem, visit this page and click on any of the text boxes on the left side. Attempts to fix by adjusting z-index in the skin.css file for div.dialogFromAndTo did not resolve ...

Utilizing Node.js within a closed intranet environment

Utilizing Nodejs's npm has proven to be quite convenient. Thus, I made the decision to incorporate it into my company's project. However, a predicament arises as my company mandates development within a closed network. This restricts my access s ...

Graphql & Node does not have a defined password parameter

I am facing an issue with my login function using GraphQL and node. Although the sign up process is working fine, I'm encountering a problem when querying the login function as it mentions that the password is not defined. Regarding AuthType const A ...

Why does Chrome consider this file a document, but Firefox sees it as an image?

I am experiencing an issue with the download GET endpoint in my Express app. Currently, it reads a file from the file system and streams it after setting specific headers. Upon testing the endpoint in Chrome and Firefox, I noticed that the browsers interp ...