NodeJS is facing a severe challenge in properly rendering HTML and its accompanying CSS code, causing a major

Once upon a time, I built a beautiful website while practicing HTML, CSS, and JS. It had multiple web pages and used Express for the backend. Unfortunately, I lost all the files associated with it and took a break from web programming for some time. Now, when I try to recreate it, I'm facing issues. When I go live with just the HTML page styled with CSS, everything looks fine. However, if I use Express, it only displays plain HTML without any styling. I've tried going back to the resources where I originally learned it, but I can't seem to find a solution.

const fs = require('fs')
const express = require('express');
const app = express();
const port = 80;
const home_html = fs.readFileSync('HTML.html')

app.get("/", (req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(home_html);
});

app.listen(port, () => {
    console.log(`The application started successfully on port ${port}`);
});

I want the website to look like this snippet, with CSS applied properly. I'm struggling to pinpoint where things are going wrong.

Answer №1

Thanks to the valuable guidance provided by @Kennard, I was able to grasp the concepts shared in the link despite facing some challenges. In an effort to assist fellow beginners who may encounter similar difficulties, I will attempt to explain the process in a more straightforward manner.

const fs = require('fs')
const express = require('express');
const app = express();
const port = 80;
const home_html = fs.readFileSync('HTML.html')

app.get("/", (req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(home_html);
});

app.listen(port, () => {
    console.log(`The application started successfully on port ${port}`);
});

While the JavaScript code functions properly on its own, there is a small issue that becomes amplified over time. Express fails to locate the stylesheet (CSS file) referenced in the HTML, resulting in inconsistencies between the files. Instead of following the specified link, it prompts:

You want to serve a file along with HTML... Fine I'll do it. 
But to avoid the mess, you have to do some thing more. Tell me the location where File is stored.
And this is the public thing mentined above

To simplify matters for novices, I recommend following this guide for creating a well-organized directory structure.

.
├── app.js
├── bin
│   └── www
├── package.json
├── public
│   ├── images
│   ├── javascripts
│   └── stylesheets
│       └── style.css
├── routes
│   ├── index.js
│   └── users.js
└── views
    ├── error.pug
    ├── index.pug
    └── layout.pug

Executing the following commands will result in this directory structure:

npx express-generator
express --view=pug myapp (myapp is name of folder you wanna generate.)

Remember the "app.js" stores all of this Javascript.

We can instruct express to search in a specific directory as follows:

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

This line essentially directs express to the 'public' folder located in the current directory to fetch files from there.

Simply place all image files used for CSS and HTML within this designated folder.

If you choose to utilize the method outlined in this link, the necessary folders are already set up for your convenience.

Always remember that the solution to any problem can be found in thorough documentation.

Feel free to upvote if you found this explanation helpful.

//Special thanks to Kennard for his invaluable assistance without which this would not have been possible.

Answer №2

Implement static serving for css files

const path = require('path')

app.use(express.static(path.join(__dirname, 'path_to_public_directory')))

Answer №3

//Store all of your website's resources in a designated public directory before executing the following command:

app.use('/static', express.static(path.join(__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

What is the hostname that npm install directs to?

My task is to set up multiple Node.js packages using npm on a standalone server that does not have direct internet access. I am able to specify an IP Address and port for access. When executing 'npm install' from the command line, where can I f ...

I am currently focusing on using websockets in combination with JavaScript and Golang servers to efficiently transmit files and

When front-end JavaScript websockets send a JSON object, it looks something like this: message_type: "1" to: "umesh" from: "moin" body: "" file: "{"filename":"reportesmtp.pdf" ,"fileextension":"application/pdf" ,"filesize":61813 ,"filedata ...

Determine the percentage of payments, similar to Upwork, by leveraging the power

Currently, I am working on developing a percentage calculation similar to what is seen on the Upwork website. The calculation appears to be accurate when derived from the base amount at a rate of 10%. For instance, if we take a base amount of 89.00, the ...

The response from getStaticProps in Next.js is not valid

While following the Next.js documentation, I attempted to retrieve data from a local server but encountered an error message: FetchError: invalid json response body at http://localhost:3000/agency/all reason: Unexpected token < in JSON at position 0 ...

How to store an imported JSON file in a variable using TypeScript

I am facing a challenge with a JSON file that stores crucial data in the following format { "login": { "email": "Email", "firstName": "First name", "lastName": "Last name", ...

Separate each element with a time gap when using the .each() function in

Below is the code snippet that I have: $('.action-button').each(function(i, obj) { $(obj).trigger('click') }); I am looking to introduce a delay between each iteration of the loop, ideally a 5-second delay. Is it achievable through se ...

The email protected function is failing to display components and is not generating any error logs

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="05776064667128776a7071607728616a6845332b31">[email protected]</a> seems to be having trouble rendering components. I've been away from React for a bit and now I ...

This is the command that includes the line "test": "tsc && concurrently "karma start karma.conf.js""

When running npm run test with the line "test": "tsc && concurrently \"karma start karma.conf.js\"" in my package.json, I encounter the error message 'Error: no test specified'. Can someone guide me on how to resolve this issue? ...

When scrolling, dynamically change the background color by adding a class

I am looking to achieve a scroll effect where the color of the menu buttons changes. Perhaps by adding a class when scrolling and hitting the element? Each menu button and corresponding div has a unique ID. Can anyone suggest what JavaScript code I should ...

Executing a function when a specific element is triggered within an ng-repeat in AngularJS

Hey there, I've been grappling with changing the limitTo filter on a specific list, but I'm encountering an issue: whenever I trigger the filter change, it applies to all ng-repeated categories. The function within my main controller is as foll ...

Error: The JavaScript function you are trying to use is not defined

Hi there, I'm new to javascript and angularjs. I've created a function in my controller to open a website when clicking on a button. However, I'm encountering an error message saying ReferenceError: openWebsite is not defined when trying to ...

Show the React component upon clicking the Add button

I recently developed a React component that reveals a new section whenever the user clicks the "New Section" button. However, I have encountered an issue - I would like the component to display multiple sections based on how many times the button is clic ...

Exploring the power of AngularJS with JavaScript and utilizing the $scope

After spending the entire day trying to solve this issue, it seems like I might be missing something simple. Here's the problem at hand: I have a well-structured Nodejs/AngularJS application that utilizes Jade for templating. The server performs certa ...

SOLVED: NextJS restricts plugins from modifying HTML to avoid unnecessary re-rendering

My current scenario is as follows: I am in the process of developing a website using NextJS (SSR) I have a requirement to load a script that will locate a div element and insert some HTML content (scripts and iframes) within it. The issue at hand: It se ...

What steps should I take to display an entirely unique regex error message in my Mongoose model?

Currently, I have successfully implemented data sanitization in my controller method: const regex = new RegExp( '^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])(?=.{8,})' ); if (regex.test(req.body.password) === false) { ...

What is the best way to activate a progress bar upon clicking a button in an HTML document?

Is it possible to make a progress bar start moving upon clicking a button using only HTML? I am new to coding (just started today) and would appreciate some guidance on how to achieve this. This is what I currently have: <input type="image" src="Butto ...

Is it possible to automatically close navigation dropdowns when the screen size changes?

I am using a bootstrap 4 navbar with dropdowns that open with CSS animation/fade-in on desktop, and a separate toggle button for mobile. Everything works fine, but when I open the dropdowns on mobile and then resize the window screen, they remain open whic ...

Adjust the color of a contenteditable div once the value matches

I currently have a table with some contenteditable divs: <div contenteditable="true" class="change"> This particular JavaScript code is responsible for changing the color of these divs based on their content when the page loads. However, I am now ...

What is the significance of z-index in relation to relative and absolute positioning?

Is there an issue with z-index when working with a div that has absolute position relative to another div? I am trying to place the absolute div below the other one, but it always appears on top. How can I resolve this problem? ...

I encountered an issue when trying to establish a connection between the environment and mongoose

This code is found in my .env file: DB_URL=mongodb://localhost:27017/ecomm The connection.js file contains the following code: const mongoose=require('mongoose') const {DB_URL}=process.env console.log(process.env) async function createConnectio ...