Troubleshooting: Style sheets not loading on a page rendered by node

Today was my first attempt at learning Node.js and creating a basic server to display a single page with a header tag. However, I encountered an error stating that the CSS file could not be loaded.

This is the code I used:

const express = require('express');
const path = require('path');

const HOST = '127.0.0.1';
const PORT = 3000;

const app = express();

//app.use("/public", express.static(path.join(__dirname, "static")));
app.get('/', (request, response) => {
    response.setHeader("Content-Type", "text/html");
    response.sendFile(path.join(__dirname, "static", 'index.html'));
});

app.listen(PORT, HOST, () => {
    console.log(`Running Server on ${HOST}:${PORT}`)
});

The HTML file:

<!DOCTYPE html>
<html lang="en-us">
<head>
    <meta charset="utf-8">
    <title>Hello World!</title>
    <link rel="stylesheet" type="text/css" href="./css/index.css">
</head>
<body>
    <h1>Hello World From Node.js!</h1>
</body>
</html>

The Error: https://i.sstatic.net/kCU6u.png

File Tree:

https://i.sstatic.net/ygM1J.png

I am in need of guidance to understand what might be missing for the CSS file to be properly linked with the HTML.

Note: The CSS file loads correctly when directly opening the HTML file in a browser.

Answer №1

You had previously mentioned using express.static(), which is a great way to serve static files.

Based on the documentation, you would utilize the following code:

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

By doing this, your CSS should load properly. Any requests like

http://127.0.0.1:3000/css/index.css
will be checked against the static directory, and if a matching file is found, Express will serve it.

If the request does not match a file in that directory (e.g., http://127.0.0.1:3000/), Express will then proceed to look for other matching routes and execute app.get('/', fn) because it matches.

As a reference, here is the full code snippet:

const express = require('express');
const path = require('path');

const HOST = '127.0.0.1';
const PORT = 3000;

const app = express();

app.use(express.static(path.join(__dirname, "static")));
app.get('/', (request, response) => {
    response.setHeader("Content-Type", "text/html");
    response.sendFile(path.join(__dirname, "static", 'index.html'));
});

app.listen(PORT, HOST, () => {
    console.log(`Running Server on ${HOST}:${PORT}`)
});

UPDATED There are two methods for utilizing express.static(), as explained in the documentation:

When using

app.use(express.static(path.join(__dirname, "static")));
(without specifying a prefix), the index.css file can be accessed at:

http://127.0.0.1:3000/css/index.css

Alternatively, when using

app.use("/public", express.static(path.join(__dirname, "static")));
(with the /public prefix), the same index.css file will now be accessible under the /public prefix at:

http://127.0.0.1:3000/public/css/index.css

This second approach may seem counter-intuitive because index.html needs to be updated to load CSS from this new prefix (and will only work when viewed via , not when opened as a local file):

<link rel="stylesheet" type="text/css" href="./public/css/index.css">

Answer №2

If you want to load your static assets, one way to do it is by creating a virtual path like this:

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

In this setup, 'public' refers to the directory where all your assets are stored. Within that directory, 'CSS' is the folder containing all your CSS files. You can then use this virtual path in the link tag's href attribute to load the CSS. For example, if you have a template file, you can include the link tag there to reference the CSS file. I've tested this with a similar directory structure and was able to fix any issues with loading the CSS. You can check out my code 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

Is there a way to ensure a Javascript alert appears just one time and never again?

I struggle with Javascript, but I have a specific task that needs to be completed. I am participating in a school competition and need an alert to appear only once throughout the entire project, not just once per browsing session. The alert will inform ...

Tips on dividing a div into two separate pages when converting to PDF

I am working on an asp.net MVC project and I need to convert a HTML div into a PDF with two separate pages. Here is an example of my code: HTML Code <div class="row" id="mycanvas"> <p>This is the first part of my content.</p> <p ...

Order of flexbox items when placed within separate divs?

Looking to rearrange the order of items using flexbox, but hitting a roadblock because one of the items I want to reorder is in a different div and not a direct child of the same parent as the other items. <div class="wrapper"> <div class="some ...

Issue with Nodejs exports causing mongoose insertion to return undefined

Struggling with a nodejs application structured into modules, I am encountering an issue where a MongoDB insertion is returning an undefined value from one of my controllers. It seems that my async function isn't waiting for the MongoDB operation to c ...

Display a blade modal upon clicking a Vuejs button

I am working on a Laravel Vue application where I need to display user records using a datatable implemented in Vue. Above the datatable, there is a button that allows users to add new records. When a user clicks on the add button, it should trigger the ...

Node.js environment variable returns a value of 'undefined'

One method I use to safeguard my bot tokens is by utilizing dotenv to keep them separate from the main app. However, a problem arises when running the code - the environment variables appear as undefined, resulting in an error message: Error: An invalid to ...

Error: Type Error when using custom App and getInitialProps in Next.js

I have a simple app built using the Next JS starter kit, and I am attempting to integrate custom functionality as outlined in the documentation: class MyApp extends App { static async getInitialProps({ Component, router, ctx }) { let pageProps = {}; ...

I need to fetch data from mongoDB by allowing the user to input a name into a search field, and then retrieve all documents that correspond to that search term

I am currently able to query the database by finding a specific key:value pair in the documents. However, I would like to enhance this functionality by allowing users to input their own search criteria as an argument in the function. Right now, I have hard ...

The error "map is not a function" occurs when trying to update the

I've encountered an issue with my links rendering on a page. I wrote a function that toggles a specific property from false to true based on whether the link is active or not, triggered by a click event. Upon inspecting the updated set of links, I no ...

Unable to establish a session on the Node server

I'm currently in the process of setting up a node server that includes login, logout, and authentication functionalities. However, I've encountered an issue with my code where after debugging, some debug information logs are being generated that ...

Is there a way to ensure that Express JS retains local variables even after server restarts?

I have set up an Express server in NodeJS v14.15.1 to handle both HTTP GET and POST requests. As part of the server operations, a key is generated and stored as a global variable within my index.js file where the express() app is located. The issue I am fa ...

When using Express, the XML response is returning an empty document

I'm experimenting with a simple API that returns XML response: const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const libxmljs = require("libxmljs"); const PO ...

A simple trick to compile and run TypeScript files with just one command!

Converting TS to JS is typically done using the tsc command, followed by executing the resulting .js file with node. This process involves two steps but is necessary to run a .ts file successfully. I'm curious, though, if there is a way to streamlin ...

After installing the latest version of Node.js, the stability of the Ionic environment

After updating nodejs from v8.1 to v12, my ionic environment is experiencing instability. Any suggestions on what needs to be updated? [abc]$ ionic cordova emulate android When running ng run app:ionic-cordova-build --platform=android, an unhandled exce ...

Nodemon fails to function when using an npm script defined in the package.json file within a Docker

Currently, I am experimenting with NodeJS and Nodemon within a Docker environment. Interestingly, I have encountered a peculiar issue while trying to execute my NodeJS application using the nodemon command directly in the docker compose file. Initially, w ...

Middleware caching for faster responses

I have been working on incorporating caching into my project using express middleware, and it seems to be functioning well. However, I've encountered an issue with an endless loop. Within my router, I have the following route: router.get('/test ...

Retrieve all elements from an array that has been imported through the fs module

To extract the values from the array jsonParsed.students[actStudent].evnetsPartaken, which may look like [1,2,0] (note: check attachments for full data), I need a way to reference each value in correlation to the event number in the configEvents JSON array ...

Resolving syntax error to enable dismissible device alerts

I am attempting to make my devise alerts dismissible. According to the bootstrap documentation found at this link, adding data-dismiss="alert" is necessary. However, when I try to implement this into my application layout as shown below, a syntax error oc ...

Transferring Large Volumes of Data via REST API

Recently, I came across a statement that claims "REST API is not suitable for Bulk Data Transfer. It's a proven fact." Despite my attempts to research this on Google, I couldn't find a definitive answer. Can someone clarify whether this assertion ...

Leveraging URL parameters in a POST request

Recently, I've encountered an issue while attempting to combine URL parameters and POST data in a single request. To provide some context, I have a form: <form method="POST" action="" class="form-inline" _lpchecked="1"> <label for="face ...