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

Customize button appearance within mat-menu in Angular versions 2 and above

Is there a way to style my mat-menu to function similar to a modal dialog? I am having difficulty with the styling aspect and need advice on how to move the save and reset buttons to the right while creating space between them. I have attempted to apply st ...

Packing third-party npm modules with Webpack for seamless integration

Description I am currently working on a project that involves nodejs, TypeScript, and express. The source files with a *.ts extension are being bundled using webpack, while the node_modules folder is excluded using webpack-node-externals. However, when I ...

Node/Express/React: The moment of anticipation after submitting a form and waiting for localhost to respond

In my current project with node/express/react, I am utilizing a form on the frontend to remove entries from the backend database: <form id="delete" action="/delete" method="POST"> <p>First name:</p> <input type="text" name="f ...

Could anyone lend a hand in ensuring that my AJAX call successfully processes the parameters?

When attempting to retrieve specific data from my database using AJAX, I encountered an issue where the call was successful when made through Postman or directly in the browser, but failed when initiated from my client. It seemed to work intermittently, re ...

Is it possible to control a Raspberry Pi through a website using Node.js?

Is it possible to utilize a Raspberry Pi running node.js to manage a device connected to the Pi through a website using wifi? Additionally, will this setup have any limitations compared to using PHP? ...

Securing a Node.js server with Azure AD OAuth 2.0

I recently developed a server in node.js and successfully deployed it to Azure WebApp. Now, I am looking to implement service-to-service authentication using Azure AD OAuth similar to this example. I have previously configured this on another WebApi serv ...

What exactly is the role of the @altfontfamily variable in Bootstrap?

Within the variables.less file, specifically in the typography section, you will find a variable named @altfontfamily. I am interested in utilizing the Alt Font Family but I am unsure of the process. Is there a specific class that needs to be called in or ...

The button in discord.js is unresponsive and does not seem to be

Hey there! I've written some code for a specific function. However, when I run the command, only the text is displayed in my channel and not the buttons. I'm puzzled as to why this is happening because I don't see any errors. Can anyone help ...

It is impossible to terminate the Mongodb server unless you are in the active terminal session

Help needed! I'm a newbie working with express.js and mongodb. I successfully set up a mongodb server in a terminal window using the command: mongod -dbpath *path name* The issue arose when I accidentally closed my text editor without terminating th ...

What is the best way to place two span elements beside each other?

Is there a way to align the name and address on the same line, with the address positioned on the right and the name on the left? Currently, the address is appearing on a separate line from the name. How can I resolve this issue? Here is the provided cod ...

Steps to retrieve a value from a promise function

My current challenge involves a function that verifies whether a device is online. Take a look at the code snippet below. const ping = require('ping'); export function checkDeviceStatus(device) { try { const hosts = [device]; let resul ...

Restricting the memory usage of node.js app

In my exploration of managing memory consumption in a node.js application, I came across the --max-stack-size and --max_executable_size options within V8. Does anyone have suggestions on how to effectively combine these with other arguments to restrict m ...

The custom radio button is not showing up on iOs Safari

My code for custom radio buttons using CSS is as follows: input[type=radio]{ display:none; } .radio-options label::before { content: "\2b24"; color:#e2e2e2; display: inline-block !important; width: 17px; height: 17px; vert ...

KnockoutJS is not recognizing containerless if binding functionality

I was recently faced with the task of displaying a specific property only if it is defined. If the property is not defined, I needed to show a DIV element containing some instructions. Despite my efforts using $root and the bind property, I couldn't ...

What methods can I use to integrate Cheerio with CSS Manipulation?

I've been working on a web scraping project using axios, cheerio, and express. However, every time I attempt to run the project, it encounters errors. For testing purposes, I am using a test page from my friend's website. Here is the code snippe ...

What is the best way to transfer information from node.js to HTML?

This is a sample code in Node.js var http = require('http'); var request = require("request"); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('Hello World!& ...

I'm having trouble finding the issue in this straightforward code snippet. Can someone pinpoint the error for

(server-side) const express = require('express'); //setting up app instance const app = express(); //middleware const bodyParser = require('body-parser'); app.use(express.urlencoded({extended: false})); app.use(express.json()); //imple ...

Finding mongoose in an array of objects nested within another object

Here is the MongoDB JSON document I am working with: { categoryId: '1', categoryName: 'Outdoors Equipments', items: [ { itemId: '1', itemName: 'Camping T ...

Content below divs that are fixed and absolutely positioned

I have a design layout similar to this (a small snippet) and I am facing an issue where the text within .content is not clickable. The positioning of #gradient is fixed due to the background image, and #empty has an absolute position to cover the entire bo ...

The carousel image slider seamlessly transitioning from the second image

I'm having an issue with the Carousel slider where it is overlapping the image from the second slide onwards. The first image loads properly, but subsequent images are not displaying correctly. Here's a reference image: CSS .slide { height: 473p ...