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

The file reading code in my Node.js application suddenly stopped working

I have a basic web application that I am currently developing using Node.js and Express. This is a breakdown of my package structure: https://i.stack.imgur.com/D7hJx.png The entries in my questions.json file are outlined below: [ { "question": "Wh ...

Retrieving CSS style values with Node.js

I am looking to design a new CSS style that includes the lowest and highest values. table[my-type="myStyle"] { width: 255.388px !important; } This code snippet is included in numerous CSS files within my style directory. ...

The HTML element does not expand to fill the entire page

I recently encountered a problem with my website. Everything was functioning smoothly until I decided to add some in-page links to a large page. After adding the links, the background no longer stretched the entire length of the page. When scrolling down, ...

Ways to incorporate a dynamic value into a chart created with chart.js?

I want to create a doughnut chart representing the number of individuals who have tested positive for Coronavirus and the number of deaths related to it. How can I transfer the same data from the top container into the chart? The confirmedCases and deaths ...

Retrieve the collection data from Mongoose and update it if it exists, or insert it if

Hello, I am new to mongodb and mongoose in conjunction with ExpressJS. Despite my efforts, I am experiencing difficulty with a seemingly simple task. var BookCounter = new Schema({ counter: {type: Number,}, book: {type: String, min: 18} }); This ...

Guide on how to trigger the next() function within a callback function

I encountered an issue where I want to send the next() function when my data is received from the python script, but I keep getting Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. const {PythonShell} = require('py ...

Browser constantly displays the message "waiting for localhost"

Within my index.js file: const express = require('express'); const router = express.Router(); // Performing tasks here router.get('/', (req, res) => { res.send('Hey! It is functioning!'); }); module.exports = router; ...

How to retrieve JSON data from a node.js server and display it in HTML

Attempting to develop a web app featuring drop-down menus that display data from a SQL server database. After researching, I discovered how to utilize Node.js to output table data in the command prompt. var sql = require('mssql/msnodesqlv8'); ...

What strategies can I use to divide lengthy words in my Django application?

My username on the site is causing overflow outside of the content box, as shown here I tried adding h1, h2, h3, h4, h5, h6 { color: #44444; overflow-wrap: break-word;}, but it didn't work. Here is the code for the profile page: All CSS styles for ...

How come the likes are not being refreshed when the button is clicked in my mongoose schema?

I am currently working on an express app using nodejs and mongoose. My main goal is to implement a JavaScript function that can update the number of likes on a post in a database directly from my ejs file. However, I have encountered troubles with this tas ...

calculating the size of an array in node.js

I received a form object from my AngularJS to Node.js and this is how it looks in the console: For two files, filenames : [object Object],[object Object] # filenames object for two files length: 2 # used object.length For one file, filenames : [object ...

Attempting to implement emit events through socket.io within route handlers

I am attempting to emit events within a route using socket.io. The route is located in another file where notifications are created, and my app.js is in the root directory where the connection to socket.io is established. I have learned about converting it ...

What is the recommended image size for Next.js websites?

According to documentation: The width of the image, in pixels. Must be an integer without a unit. The height of the image, in pixels. Must be an integer without a unit. https://nextjs.org/docs/api-reference/next/image Different devices come in various ...

Guide to generating a dropdown menu and linking it with data received from a server

I am completely new to Angular and recently received a project involving it. My task is to create a nested dropdown list for Json data retrieved from a server using Rest Api calls. The data contains a Level attribute that indicates the hierarchy level of ...

The styles defined in CSS do not have an impact on EJS templates that have GET route paths stacked

I have a CSS file located in the public directory and two EJS templates in the views directory. The CSS file works fine when using this route: app.get('/theresa', (req, res) => { res.render('templates/home') }) However, when I ...

How can a user add a unique header to a Webbrowser control for all requests using C#?

My current setup involves using C# and .NET 3.5. One of the functionalities I'm working on involves adding a custom header to the Navigate() function in a web browser control. The code snippet for this operation looks like the following: var myUrl = ...

Send a quick response and retrieve it in the client application

My goal is to allow the user to send data to the server, where it will be saved into a database. After this process, I want to send a message back to the user (which could include the ID of the newly added object). However, I have been struggling with my c ...

The call stack limit has been exceeded due to the combination of Node, Express, Angular, and Angular-route

Embarking on a new SPA journey, my tech stack includes: Back-end: NodeJS + Express Front-end: Angular + Angular-route. Twitter Bootstrap Underscore Having followed many tutorials with similar stacks, my project files are structured as follows: pac ...

Trouble with Metro UI Library: CSS not loading properly

I am having trouble with the navbar CSS on my website while using the Metro UI CSS library. Check out my HTML code: <!DOCTYPE html> <html lang="en"> <head> <title>TelePrint Blog</title> <link rel="stylesheet" href= ...

What is the best way to transfer information between two React.js files?

I am currently finding it inefficient to pass data from App.js to another .js file within React by constantly reading and writing from local storage. I would prefer to only retrieve data from local storage once when the App.js component mounts. App.js: ...