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

Merge two distinct JSON objects obtained through an API request using Javascript

Struggling with my currency conversion project, I'm trying to display JSON response results on my website but can't seem to make it work. The code snippet below, .then((response) => { return response.json(); }) .then((jsonRespo ...

Toggle divs by using a checkbox (Vue.js)

On my authentication page, I have implemented a checkbox that I want to use to toggle between Sign Up and Sign In forms. When the checkbox is clicked, it should display the Sign Up form, and when it's unchecked, it should show the Sign In form. I fou ...

Creating custom validation in Vuetify for password confirmation is essential in ensuring that

While developing a Vue.js template, I encountered a scenario on the sign-up page where I needed to compare passwords during user registration. To achieve this, I implemented a custom validation rule in the code snippet below: <v-text-field label=" ...

Efficiently Minimize Bootstrap Components Upon Clicking the Link

I've successfully created a navigation menu that expands and collapses without using a dropdown feature. However, I'm encountering an issue where I can't seem to toggle the div when clicking on a menu link. I attempted to use JavaScript to c ...

"Enhance user interactions: Zooming in on input fields in

Currently, with the latest version of iOS (14.4), there is a zoom effect on any input box that receives focus, unless the input has a font size of 16px without focus. While this may not seem like an issue initially, once focus moves away from the input bo ...

What is the method for extracting JavaScript code as data from a script tag?

I have a file external (let's say bar.js) function qux() {} Then in my webpage, I include it using the script tag: <script type="text/javascript" src="bar.js"></script> I am looking for a way to retrieve the JavaScript code from within ...

Unable to retain the textbox value upon the initial button click in ReactJS

Can you please assist me? I am trying to save textbox data to hooks, but when I click the save button, the data is not immediately saved to my useState. I have to click the save button again in order to save it to the hooks. Here are the relevant code sni ...

How can you organize A-Z/Date information retrieved from router.get?

Simple question: how do I arrange my posts by date in the data? router.get('/', async (req, res) => { try { const posts = await Post.find() res.json(posts) } catch (err) { res.json({message: err}) } }) ...

Tips for creating a navigation bar item that displays a component depending on its active state

Trying to enhance the modularity of my code but facing difficulties. I have a tab bar and I want to render a specific component based on the clicked nav/tab item. Struggling with passing props properly, as the current code only recognizes the children valu ...

Combine two events in jQuery using the AND operator

Can I create a condition where two events are bound by an AND logic operator, requiring both to be active in order for a function to be called? Let's say you have something like this: foobar.bind("foo AND bar", barfunc); function barfunc(e) { al ...

Guide to deploying a NodeJS form application using the Zeit Now server

Currently, I have a simple node.js form processing application running on a Zeit Now server and deploying it using the Now CLI scripts. Even though this Node app works perfectly fine on my localhost with the specified port number (like so: http://localhost ...

Sorting data within a populated field in MongoDB using Mongoose

Seeking assistance with sorting personnel by rank in MongoDB. I have two collections: CollectionPerson and CollectionRank. CollectionPerson: _id, name, {rank_id} CollectionRank: _id, RankName, level I want to display a list of personnel sorted by their ...

Unable to retrieve data from MongoDB with the given query

I have encountered a problem while following the documentation mentioned in this link. To build my website, I am using mongodb, express, and node. In my application, I have a user collection that stores users' data. I intend to display a JSON repres ...

What is the best way to display multiple .ejs files in a nested structure using Node.js and Express?

Is there a way to display multiple .ejs files in a nested structure? Consider the code snippet below: var mysql = require('mysql'); var ejs = require('ejs'); exports.index = function(req, res){ if (req.method=='POST'){ ...

jQuery's Ajax feature fails to transmit information

I am facing an issue with my asp.net core backend project where my method is not receiving the data sent by jQuery ajax https://i.sstatic.net/O9wYg.png Here are the scripts I am using to send data: function ChangeCount(productId, count) { $.ajax({ ...

The placement of the React.js/Next.js Loader is incorrect on the page

While I was trying to display a Loader over everything during data fetching from my API, I encountered a situation where the Loader was not appearing at the expected top level but inside the page itself. Even though the HTML tree showed it at the top level ...

Develop a schema for an array of arrays in NodeJS using mongoose

Looking to establish a database schema for storing the following data: { name : "xyz", admin : "admin", expense : [ jan: [{expenseObject},{expenseObject}], feb: [[{expenseO ...

Is there a way to use the command line (apk --update add) to install the most up-to-date version of node.js with the latest features, rather than the LTS version recommended for the majority of users?

My Docker file is based on 'python:alpine' image. I want to have both python and node.js installed in the container, so I begin with a python image. How can I install the most recent version of node.js ('Current latest features') in t ...

Contrast between PHP and JavaScript output texts

Hey everyone, I'm dealing with a bit of an awkward situation here. I am trying to return a string variable from PHP to JavaScript and use it for a simple comparison in my code. However, the results are not turning out as expected. Initially, I send a ...

Storing an image to an S3 bucket in node.js from a provided URL

I am looking for a way to save images from a URL directly to S3. Previously, I managed to allow users to upload profile pictures using the code found in the documentation (link here): uploadUserImage: function(req, res) { var userName = req.params.us ...