Using Node JS to serve an HTML file along with cascading style sheets

As I delve into pure node.js, I encountered an issue related to the HTTP protocol. After spending hours searching and testing my code, I finally managed to serve my HTML page with CSS successfully. Take a look at my code snippet below:

const server = http.createServer((req, res)=>{
if(req.url === "/"){
    fs.readFile("index.html", "UTF-8", function(err, data){
        res.writeHead(200, {"Content-Type": "text/html"});
        res.end(data);
    });
}else if(req.url === "/styles.css")){
    var cssPath = path.join(__dirname, 'public', req.url);
    var fileStream = fs.createReadStream(cssPath, "UTF-8");
    res.writeHead(200, {"Content-Type": "text/css"});
    fileStream.pipe(res);
};
});

However, I'm puzzled by how it works. When I only type "/" in the browser and not "/styles.css," why does the CSS still display without seeing "/styles.css" in the URL bar? I suspect it has something to do with the design of the HTTP protocol. Can anyone provide insight or explanation on this matter? Thank you!

Answer №1

When you enter /styles.css into the address bar, you will be able to view the source code of the CSS file. For instance, click on this link.

If you type /, the browser requests the server for / and receives an HTML document in response.

The browser then processes the HTML document, likely containing something like:

<link rel=stylesheet href=/styles.css>

Subsequently, the browser asks the server for /styles.css which is a CSS file. The CSS is then applied to the HTML document.

The reason why /styles.css does not appear in the address bar is because you are currently viewing /. The CSS file is simply another necessary resource for the complete rendering of the HTML document represented by /.

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

Encountering a login issue with a 402 error code - "Payment Required"

I'm having trouble logging in. The user is already in the database, but when I try to login, it displays the following error: POST http://localhost:3000/api/v1/users/login 402 (Payment Required) If I register for the first time and then log in, ever ...

Ways to change columns into rows with CSS

Hey there! I'm looking for a way to convert columns into rows and vice versa. In my table, I have both column headers and row headers on the left side. The row headers are simply bold text placed next to each row to describe its content. I want to op ...

What is the best way to troubleshoot a peer dependency error in my Angular 10 project while utilizing npm?

I am currently in the process of upgrading my Angular 10 project, which is running on Node 14.x and npm 6.14.x. When I run the following command: npm ls I encounter a series of issues related to peer dependencies in npm. The errors are as follows: "p ...

having difficulty transmitting data or interacting with certain buttons on the site using selenium in python

Struggling with reading the HTML of a specific website as I try to perform operations on it. Here's the URL: Encountering 2 issues: Attempted to input a date range, or set it to max for at least 30 years of data. Below is my code snippet trying to s ...

Can Angular 2 Material Tabs be dynamically filled with a For Loop subscription?

Is it possible to populate a dynamic number of tabs on an Angular 2 website using a For Loop that subscribes to data from a database service? My dataset is categorized by Classes A, B, and C, each with Sub-Classes 1 and 2. I want to dynamically create thr ...

What is the best method for organizing data in rows and columns?

I attempted to use my map function to iterate over the data and display it, but I struggled to format it into rows and columns. The requirement is for 5 fixed columns with dynamically changing rows, making array indexing impractical. Here is the code snip ...

Navigating without the need for a mouse click

Is there a way to automatically redirect without user interaction? I need the redirection to happen without clicking on anything <script> setInterval(function(){ window.location.replace("http://your.next.page/"); }, 5000); // Redirec ...

"The event triggers the function with an incorrect parameter, leading to the execution of the function with

Currently, I am working with a map and a corresponding table. The table displays various communities, each of which has a polygon displayed on the map. My goal is to have the polygons highlighted on the map when hovering over a specific element in the tabl ...

Looking to manipulate the form submit data before it is submitted using the standard submit event and jQuery? Read on to learn how to remove, enhance, or change

Is there a way to extract data from a form like the one below? <form action="/search/search" data-remote="true" data-type="json" id="search_form" method="get"> <div class="input-group"> <span class="input-group-addon"> <i ...

Troubleshooting: Resolving the error message "SyntaxError: Unexpected token '<'"

I am currently facing an issue with my code that is supposed to use LAT&LONG data saved in a txt file and display it as a Google Map in HTML. However, the PHP function to import the txt file is not working at all. Any suggestions on what might be causi ...

Creating a function within document.ready using jQuery is a common practice for ensuring that

I am currently working on creating a straightforward function that will replace an attribute when called using onclick="changeYoutube('XXXXXX');" within a link tag. However, I am encountering an issue where it says calling "changeYoutube" is resu ...

Verifying the angular form without the need for a submit button

I'm currently utilizing angular.js form validation and I'm looking to implement validation without the use of a form submit button. Below is my HTML code: <form name="userForm"> <input type="hidden" ng-model="StandardID" /> < ...

Creating custom styled CSS with SASS through Node and Grunt

Hey there, I'm in the process of creating an asset builder app with Node and Grunt. My main goal is to manage multiple projects and concatenate/compile/minify the output. So far, things are going well. I've managed to concatenate my JS files (al ...

Unable to Locate CSS File in Separate Folder in HTML

I am struggling to link my stylesheet from a different directory to my HTML files, even though I believe I am using the correct method. Could it be that I am targeting the wrong level? '-' represents levels Take a look at my file structure: my ...

Tips for incorporating a CSS transition when closing a details tag:

After reviewing these two questions: How To Add CSS3 Transition With HTML5 details/summary tag reveal? How to make <'details'> drop down on mouse hover Here's a new question for you! Issue I am trying to create an animation when t ...

Prevent parent element from changing color when child element is clicked

Check out my HTML: .imageURL:active .image_submit_div { background-color: #ccc; } .image_submit_div:active { background-color: #e6e6e6; } <div class="image_div"> <label for="id_image" class="image_submit_div"> <h3>+ add ...

How come my HTML form keeps refreshing instead of displaying an alert after submission, even though I've included onsubmit="return false"? Additionally, it seems to be throwing an error

Why is this basic HTML and JavaScript code not functioning properly? Instead of alerting once the form is submitted, it refreshes the page and throws an error. It has also been reported to sometimes throw a CORS error when using 'module' as scri ...

How come padding-bottom isn't effective in increasing the position of an element?

My goal is to adjust the position of the orange plus sign (located in the lower right corner of the screen) so that it aligns better with the other icons, directly below them. I've tried using padding-bottom, but it doesn't seem to work, while pa ...

Separate configurations for Webpack (Client and Server) to run an Express app without serving HTML files

I am currently developing an application with a Node Backend and I am trying to bundle it with Webpack. Initially, I had a single Webpack configuration with target: node. However, I encountered issues compiling Websockets into the frontend bundle unless I ...

What is the best way to configure routes using Express and NGINX?

I am currently in the process of setting up an Express server with NGINX as a reverse proxy. My goal is to have NGINX handle serving static files, while Express takes care of dynamic content. The issue I'm encountering is when I try to access (websit ...