NodeJS seems to be having trouble with external CSS files

My nodeJS project uses an external CSS file to style the HTML page. Here is how my file structure looks:

ProjectFolder  
----server.js  
----index.html  
----style.css

This is how my server.js file looks like:

var http = require('http');
var fs = require('fs');
var $ = require('jquery');

function onRequest(request, response) {
    response.writeHead(200,{'Content-Type':'text/html'});
    fs.readFile('./index.html',null, function (error,data) {
        if(error){
            response.writeHead(404);
            response.write('File not found')
        } else {
            response.write(data);
        }
        response.end();
    });
}

http.createServer(onRequest).listen(8081);

Below is the structure of my HTML page:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href='style.css'>
<script src="https://ajax..."></script>
<script>
   ........ 
</script>
</head>
<body>
<div id="inputDiv">
<h1>User Details</h1>
</div>
</body>
</html>

Here is a snippet from my CSS file:

div {padding-bottom: 10px}
label {float: left; width: 6em; text-align: right;padding-right: 4px}
input {text-align: left;}
textarea {alignment: right;}

When I run node server.js and access index.html, the page loads without any CSS styling. However, when I open the HTML page directly in the browser, the styles are applied correctly. What could be causing this issue?

Answer №1

Your server is struggling to serve the CSS file. Give it a break and try accessing the file on your own. It's not going to cooperate.

When you're running your file from the filesystem file:///, the style.css will load just fine because it's right there in the same spot.

However, if you use something like localhost/index.html, the browser will attempt to fetch localhost/style.css but the nodejs server mentioned won't handle it.

Check out this answer for some assistance.

If you want an easier time setting up a web server, consider using Express or Koa instead.

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

Creating a character jump animation on an HTML5 canvas

While following a tutorial on creating character animations, I encountered an issue. The tutorial, located at , made it easy to make the character move left (the right movement was already implemented). However, I am struggling with how to animate the char ...

Connecting a secret parameter to a designated radio option within a form (PHP/MySQL/HTML)

I am currently building a PHP form that connects to a MySQL database. Each question in the form requires a simple yes or no answer. The challenge I'm facing is with submitting a hidden value when the user selects 'No' for a question. This ...

What is the process for importing a JavaScript export file created from the webpack.config file?

Issue at Hand In the process of testing APIs, I encountered a dilemma in setting up either the DEV or Production environment. This involved configuring API endpoints for local testing and preparing them for production use. To achieve this, I utilized NOD ...

Show off on social media but not in person

Check out this HTML snippet: <div class="d-sm-flex flex-sm-row flex-sm-row-reverse"> <div class='ml-2'></div> <div class='ml-2'></div> <div class='ml-2'></div> </div> ...

Which specific file is being requested when a forward slash (/) is placed immediately after the website URL?

Is it just me being clueless, or is there something unusual about this URL format? I've come across URLs like http://www.example.com/?p=1 quite often and I'm curious to know what exactly is being accessed by it. I usually use URLs such as http:// ...

Troubleshooting Problem with Responsive Bootstrap Navbar

I've been working on creating a menubar using Bootstrap where the logo image is centered instead of being on the left side of the bar. However, I'm facing an issue where the right links in the menu go off the screen. When I view the page with a w ...

SVG images are not perfectly aligned with surrounding elements, causing a noticeable discrepancy, which becomes even more pronounced when they are being animated

I've been experimenting with creating animated 3-D bars in a bar graph. To ensure there are no issues with stretching or aspect ratio, I decided to split each bar into three parts: (1) an SVG for the top of the bar, (2) a div with adjustable height fo ...

Tips for saving variable state using closure

I am working on a function that needs to be called multiple times, and this function will add elements to my HTML: class MyClass { addElements(elements) { const parentElement = $("#parent").find("#other-element"); for (let element of elements) ...

There is no class present in the @Apply layer with Tailwind styling

I've been searching for what seems like a simple solution, but I can't seem to find it. While researching similar issues, I noticed that people were having problems with the Hover style and extra white space after it, which is not the issue in my ...

Looking for a way to locate a string for a Boolean field in mongoDB?

I am dealing with a situation where I have a field name and criteria to search for in a collection. However, the types of fields I am working with vary, ranging from String to Number to Boolean. I attempted the following approach: const fieldName1 = &ap ...

SafeTransferFrom function in Binance Smart Chain experiencing issues with transfer comments

After successfully deploying and verifying an ERC721 smart contract on BSC's testnet, I was able to mint and award new ERC721 tokens. The next step is transferring these tokens between wallets. Everything seems to be going smoothly so far, but I would ...

How can elements in HTML emails be repositioned further down the page?

I am currently designing an HTML email, and I have a very basic element (ul) that I need to reposition lower on the page. After consulting Campaign Monitor's guide, it seems that they do not support negative margins or the position: absolute parent / ...

Is there a Safari glitch related to floating elements?

I stumbled upon a strange issue with the layout I've been working on, and it led me to this concise code snippet that seems to be causing misrendering in desktop Safari. It appears that the div#shim element is what's triggering the text misrender ...

Find the second element beneath the mouse cursor that is not a direct ancestor of the first element

I am currently developing a card drag-and-drop board using HTML5 inspired by Trello. My focus right now is on connecting the lists to specific list slots/containers. My challenge lies in determining which list container is positioned beneath the mouse po ...

Tips for bundling and upgrading a nodejs program on FreeBSD without any cost?

I am trying to streamline my express web server by packaging it as a single executable file, similar to .WAR files for Java applications, in order to install it on FreeBSD without the need to install NodeJS or run 'npm install'. I have explored ...

Showing a div with 2 unique data attributes - such as displaying Currency and Quantity

My E-Commerce website is created using HTML, JavaScript, and PHP. On the product details page, users can add products to their cart, so I show the total cart value. I need the total amount displayed in a decimal number format (10,2). Currently, when a u ...

Passing a query parameter in an Express route

Hello there, I am a newbie when it comes to nodejs and express, and I am currently working on implementing a simple functionality. I have managed to write some code that effectively sends my get requests to the correct route (in this case, a service where ...

Opting for CSS3 transitions over jQuery animate

Currently, I am working on animating a block of HTML that involves fading in (opacity) and slightly moving from the left (margin-left)... $('.latest-stats').delay(1000).animate({ opacity: 1, marginLeft: '55px' }, 1000, function () { ...

Receiving an error of "undefined" when trying to capture the selected

One issue I am facing is capturing the selected user option and sending that value in a post request. Let's put aside the post part since it's not directly related to the main question at hand. Currently, the value is showing up as undefined. ...

The website experiences a sudden crash shortly after launching, displaying the error message "EADDRINUSE" for port 80

PROBLEM I have a react-based website running on a node-express server. My backend server is working fine on port 3000, but the website on port 80 keeps crashing. When I use pm2 to start my website (https://www.edvicer.com) with the command pm2 start serv ...