Guide to setting up a node.js server that serves HTML files with CSS styling

I am currently working on setting up a simple node.js server for my HTML using http and express.

Everything is functioning properly, but the CSS is not displaying as expected.

Here is the code snippet for my server setup:

const express = require("express");
const app = express();

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

var router = express.Router()

app.use('/',router)

router.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.htm")
})

app.listen(8080)

And here is the code for another server I created using http:

const http = require("http")
const port = 8080
const fs = require('fs')

const server = http.createServer(function(req,res) {
    fs.readFile('./index.html', (error, data) => {
        if(error) {
            res.writeHead("404")
              res.write("Error. File not found.")
        } else {
            res.use
            res.write(data)
        }
        res.end();
    })

})

server.listen(port, function(error) {
    if(error) {
        console.log(error)
    } else {
        console.log("server is listening on port " + port)
    }
})

Below is my full HTML code:

<!DOCTYPE html>
<html lang="en">
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Domodinak</title>
        <link rel="stylesheet" href="css/style.css">
    </head>
    <body>
        <p>Hello world</p>
    </body>
</html>

Additionally, here is the CSS included:

body {
    background-color: deeppink;
}

If you have any insights or solutions to help with the CSS display issue, please share. Thank you!

Answer №1

Ensure that you are correctly referencing the css folder within your project structure. It is recommended to store your static files in a directory named public, and then organize your files into separate folders such as js and css. For instance, let's say you have a src folder for your express server file, and alongside it, a public folder with a subfolder called css. Place your stylesheet file inside the css subfolder, and the HTML file directly in the public folder. Update your code as follows:

const express = require("express");
const path = require("path");
const app = express();

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

// var router = express.Router()

// app.use('/',router)

// router.get("/", (req, res) => {
//  res.sendFile(__dirname + "/index.htm")
// })

app.listen(8080)

Your project structure should resemble this:

|-public -| css -| style.css
          index.html
|-src -| app.js

Start the server and navigate to localhost:8080 in your browser. It will serve the index.html from the static directory you specified earlier.

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

Attempting to migrate a HTML website to WordPress has proven to be a challenge as only the content is visible, with the CSS failing to load properly

I'm looking to convert an HTML site into a WordPress site while keeping the same theme intact. Even after adding 'wp_enqueue_style' to the functions.php file, the CSS file is not being recognized by WordPress. functions.php <?php f ...

What is the best method to host my Vuejs frontend files using my node/express server?

Currently, I am configuring two routes in Express - one for the home page and the other for the admin page. However, I am struggling to find comprehensive documentation on integrating Vuejs with Express in a way that allows me to serve both pages simulta ...

An issue has occurred [ERR_HTTP_HEADERS_SENT]: it is not possible to adjust headers once they have been sent to the client. It is not possible to redirect to a page other than

I'm currently working on a program where I want the server to redirect users to a different page if incorrect details are entered. The issue I'm facing is that every time I attempt to use res.redirect() with another web page as a parameter, I rec ...

Steps to include a HTML webpage within another page

I need assistance with a scenario involving two separate HTML pages on different servers. Merchant Form - Server A Payment Form - Server B Here's the desired scenario: The user completes all necessary fields on the Merchant Form and clicks submit. ...

Steer your keyboard attention towards the parent element that embodies a list

My implementation focuses on making drop down menus accessible via keyboard input using HTML/CSS and JS/jQuery events. The goal of keyboard accessibility includes: Tab key to navigate the menu elements. Pressing the down arrow key opens a focused menu. ...

Is there a way to track and detect alterations to an element using JavaScript or jQuery

Can I detect the addition of a specific CSS class to an element without having to create a new event? ...

How can we use fetch to grab some data?

I put together an Express application quickly, here's how it looks: const express = require("express"); const app = express(); const port = 3000; app.get("/content/1/", (req, res) => res.send("Thinking about taking out a new loan? Call us today. ...

Issue with importing styles within a media query

I am having trouble importing a style that is based on a media query. When I try to import the styles, it doesn't seem to work. However, if I directly include the styles within the media query itself, they show up on the page. For reference, you can ...

Unleash the potential of a never-ending expansion for grid cells on Canvas

ts: templateStyle = { display: 'grid', 'grid-template-columns': 'calc(25%-10px) calc(25%-10px) calc(25%-10px) calc(25%-10px)', 'grid-template-rows': '150px auto auto', 'grid-gap ...

What could be causing Laravel Sail NPM to display the error message 'unsupported version of Node.js'?

In the midst of a Laravel 8 project using Docker, I find myself knee-deep in SCSS design. However, a hurdle arises when attempting to compile my SCSS files. NPM insists that my Node version is outdated at 12.x, even though within my container I am actually ...

Do you know the term for when JavaScript is utilized to display specific sections of a png image?

Imagine you have an image file in the format of a PNG which includes various icons intended for use on a website. How can JavaScript be utilized to choose and showcase a specific icon from that image? It's a technique I've observed in practice, b ...

Covering the entire screen, the Div element takes up the entirety of

Just like with other pages, the main div always takes up the entire screen visible to the user. As they scroll down, another div becomes visible: example1 , example2 Regardless of the screen size, the main div will always fill the space visible to the use ...

Unable to find user authentication details in request sent from Android application to NodeJS server

I'm currently working on an Android app that utilizes a NodeJS backend server. My main issue lies in the authentication process for users when navigating to different pages post-login. After logging in, I save the set-cookie value in SharedPrefs. Sub ...

Position a modal in the vertical center with scroll functionality for handling extensive content

Looking for ways to tweak a Modal's CSS and HTML? Check out the code snippets below: div.backdrop { background-color: rgba(0, 0, 0, 0.4); height: 100%; left: 0; overflow: auto; position: fixed; top: 0; width: 100%; z-index: 2020; } ...

Can anyone provide guidance on locating the parent of a pseudo element with Selenium WebDriver?

Is there a way to retrieve the parent web element of a pseudo element (if we can call it the parent) using JavaScript? I know that Selenium's methods for searching for web elements are not suitable for pseudo elements, but JavaScript does allow manipu ...

Why is the helpers folder so important in an Express application?

Exploring the ideal hybrid folder structure to meet our needs is my current project. After sifting through numerous resources and sources, I stumbled upon a folder labeled helpers housing files with a .js extension. |-- app | |-- controllers | | `- ...

How to Upgrade Node and NPM on Google Compute Engine?

Currently, my Google Compute Engine VM is utilizing a Node.js v6.16 image. I am interested in updating to the latest version as I need async functions which are not supported in v6. How can I go about updating this? ...

Using Node.js to download files with like wget, unzip them, and convert them to JavaScript without saving to

Currently, I am working on a script for a nodejs/express server-side application using the libraries request, unzip, and xml2js. The goal of this script is to fetch a zip file from a specified URL, extract an XML file from it, and then parse that XML into ...

nodejs - pkg encountered an error: only one entry file or directory should be specified

I am currently facing issues with packing my simple cli node script using pkg. After running the command below: host:~ dev$ pkg /Users/dev/Desktop/myscript/ --target node14-macos-x64 node14-linux-x64 node14-win-x64 I encountered an error in the terminal: ...

Javascript - Conceal a Dynamic Div Depending on its Text

I have a unique table that generates dynamic Divs with ID's that count as they are created in the following format: <div id="dgpCheckDiv10_0"> <input Delete </div> <div id="dgpCheckDiv10_1"> text2 </div> Some of t ...