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

What are some strategies for implementing updates seamlessly without causing any disruptions to the service

As I prepare to embark on a project using Node, Express, and Mongo, there is a crucial question that needs resolving. Picture this - the application is up and running smoothly. Eventually, changes will need to be made and deployed. While development mode ...

What is the process for implementing a third-party component in my web application?

After some experimentation, I've discovered that it's necessary to include the link to the css files in the header and then mention the link to the js files before the closing tag. However, I encountered difficulties when trying to use a compone ...

Grid layout with card tiles similar to Google Plus

I'm looking to develop a scrolling grid with card tiles similar to Google Plus that has three columns. I am currently using Material UI, but I can't seem to find the right functionality for this. I have experimented with the standard Material UI ...

Navigate the user to various pages in a Node.js application based on login status

Looking for guidance on a login system within my application? I need to redirect users based on their roles. Below is the code for the login controller, along with node.js snippets and the login HTML page. Any help would be appreciated. Login.html - < ...

When working on a MEAN web application, encountering HTTP responses like 403 or 500 from the Express server can sometimes go unnoticed and not be properly handled in the errorCallback function within

Within my Node web app, there is a situation where an HTTP GET request is sent in one of the Angular controllers. At the same route defined in Express, somewhere in the route logic, an HTTP 500 response (also tried 403 Error) is also being sent. However, i ...

Arranging elements on a website using CSS styling

I'm interested in creating a button <Button id="Button" text="Hey" />. I would like to know how I can position it on a webpage exactly where I want it, rather than it just appearing randomly without content. ...

Error Deploying Firebase Functions

I've been dedicated to this project for quite a while. I have deployed it numerous times without any issues. However, after revisiting the project following a month-long break, I encountered an error upon running firebase deploy --only functions: i ...

Error with infiniteCarousel in Internet Explorer versions 7 and 8 when using jQuery

Hello everyone! I've run into a little issue with some jQuery code I'm using. It was working fine before, but after making several changes and improvements, I can't seem to figure out what the problem is. I keep getting JS errors in both IE7 ...

How to dynamically change the color of an AngularJS element based on a condition?

As someone who is new to AngularJS, I am currently working on changing the color of a table element to yellow if the user has voted on a specific choice. <div ng-show="poll.userVoted"> <table class="result-table"> <t ...

Encountering a NullPointerException while trying to load a resource from a directory that is not within

I'm working with JavaFX and trying to incorporate a CSS file into my scene. scene.getStyleSheets().add(Main.class.getResource("res/application.css").toExternalForm(); An NPE is being thrown. I suspect it's because the css file isn't locate ...

Changing the size of a responsive navigation bar with React and adjusting it based on the window.scrollY position switches between collapsed and un

I'm struggling to create a responsive navbar that automatically adjusts its size once it surpasses the height of the navbar (currently set at 80px). However, when I scroll to around the 80px mark, it starts flickering between the collapsed and expande ...

Creating a design with two divs split by a diagonal line using CSS

Is there a way to make two divs span the full width of the page while being divided in half by a diagonal line using CSS? I am working on a slider and once completed, I need to add content to both parts. Any ideas on how to accomplish this with two divs? ...

Troubleshooting IE compatibility issues with jQuery .hide() method

I am encountering a curious issue with hiding span elements using CSS (display: none;). Upon page load, I expect the first span element to be displayed, which it does in all browsers except IE7. This anomaly has left me perplexed as there is no unusual cod ...

Looking to gather the total number of documents before conducting a grouping operation in an aggregate query in MongoDB

Before grouping the data in my query, I want to get the total count of all documents. This is important because once I have the count, I can easily calculate the percentage for each student. I tried using $count but it interfered with my ability to group t ...

Choose the data attributes you want to include and attach them to input elements using plain JavaScript

Creating a User Information form with a select element containing four options, each with data attributes. Under the select are input types to populate the data attributes when selected. Looking for help in achieving this using plain JS and onchange event. ...

Understanding the role of "payload" in jsonwebtoken

I'm interested in utilizing JSON Web Tokens for user validation and I'm getting ready to use the jwt.sign method. However, I find the term "payload" a bit confusing based on the definition found on Wikipedia, which states that in computing and te ...

When using npm install with --save-exact, the exact version specified is not being

Details about my setup: Node.js version: 6.17.1 NPM version: 6.14.4 After executing the command npm install --save --save-exact <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="660b0c0b0a265248534857">[email protected] ...

Discovering more about this topic

Looking for a way to create an expandable box that enlarges when "read more" is clicked, revealing text below it. And also looking to add a button that closes the expanded text back up. Experimented with the toggletext JavaScript command, as found on this ...

Switch out the content when the button is clicked

Seeking a code snippet to enable clicking a button (Button labeled "Next") for replacing existing code on the page with new code. Current code below should be replaced, starting from the score counter section. Please excuse any messy code as I'm new a ...

Node.js has no trouble loading HTML files, however, it seems to encounter issues when trying to

Having a bit of trouble with my JavaScript skills as I try to load my index.html file (seems like it should be the 5th easiest thing to do in JavaScript). Let me get straight to the point; when I manually open my index.html, it loads perfectly WITH the CS ...