Basic node.js server that responds with HTML and CSS

I have successfully created a basic http server to send an HTML file as a response. However, I'm struggling with how to also send a CSS file so that the client can view the HTML page styled with CSS in their browser.

Here is my current code:

var http = require('http');

var fs = require('fs');
var htmlFile;

fs.readFile('./AppClient.html', function(err, data) {
    if (err){
        throw err;
    }
    htmlFile = data;
});

var server = http.createServer(function (request, response) {
      response.writeHead(200, {"Content-Type": "text/html"});
      response.end(htmlFile);
    });

//Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

console.log("Server running at http://127.0.0.1:8000/");

After some attempts, here is what I've tried (but it doesn't seem to work - the client only sees the CSS content):

var http = require('http');

var fs = require('fs');
var htmlFile;
var cssFile;

fs.readFile('./AppClient.html', function(err, data) {
    if (err){
        throw err;
    }
    htmlFile = data;
});

fs.readFile('./AppClientStyle.css', function(err, data) {
    if (err){
        throw err;
    }
    cssFile = data;
});

var server = http.createServer(function (request, response) {
      response.writeHead(200, {"Content-Type": "text/css"});
      response.write(cssFile);
      response.end();

      response.writeHead(200, {"Content-Type": "text/html"});
      response.write(htmlFile);
      response.end();
    });

//Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);


console.log("Server running at http://127.0.0.1:8000/");

Here is the HTML file:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="AppClientStyle.css">
</head>
<body>


<div class=middleScreen>

<p id="p1">Random text</p>

</div>

</body>
</html>

And here is the CSS file :

@CHARSET "UTF-8";

.middleScreen{
    text-align:center;
    margin-top:10%;
}

Just for clarification, I want to avoid using Express in this scenario as I am doing this purely for learning purposes.

Answer №1

Within your initial code snippet, you've set up a web server that returns the body of your HTML file regardless of the requested URI from the browser.

While this is all well and good, in the second snippet, you're attempting to send a secondary document to a closed response handle. To grasp why this approach fails, it's essential to comprehend how HTTP operates. HTTP primarily functions as a request->response protocol where the browser requests content and the server either sends that content or an error message back to the browser. Therefore, sending a second response to the browser unprompted is not the appropriate course of action.

So, how can you prompt the browser to request a second document? The solution is quite simple - within your HTML file, there likely exists a

<link rel="stylesheet" href="AppClientStyle.css">
tag. This tag prompts the browser to request AppClientStyle.css from your server. You can cater to this by introducing a switch or if statement in your createServer code to execute different actions based on the requested URL.

 // Your script here

Upon accessing your server at http://localhost:8000, your HTML file will be served initially. Subsequently, the contents of that HTML file trigger the browser to request http://localhost:8000/AppClientStyle.css.

It's worth noting that you can enhance the flexibility of your server by serving any file present in your project directory:

 // Your enhanced script here

If you start this setup in the same directory as your HTML and CSS files, it should suffice for personal learning or local development purposes despite its simplicity, error-prone nature, and lack of security measures.

Remember that while the above method works, utilizing Express would streamline the process significantly. If you need convincing, consider trying it out:

 // Instructions for setting up Express

By following these steps and running your modified script, navigating to http://localhost:8000 in your browser becomes a straightforward task.

Answer №2

Embed CSS directly into your AppClient.html file. Different methods can be used:

Using an External CSS File

First, create a styles.css (or any other name) file in the same location as your HTML file. Next, include the following code:

<link rel="stylesheet" type="text/css" href="styles.css">

In the <head> section of your HTML document.

OR

Directly in your HTML File

Add the following code:

<style>
    YOUR STYLES GO HERE
</style>

To the <head> section of your HTML document.

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 best method for obtaining a modified image (img) source (src) on the server side?

Having some trouble with a concept in ASP.Net that's causing me quite the headache. I am fairly new to ASP.Net and struggling with something that seems much easier in PHP. I created an img element with an empty src attribute : <img runat="server" ...

Unusual increase in the Date() function hour on March 12, 2017

I encountered an issue where creating a new Date() object for March 12, 2017 with the hour set to 2am displays as 3am when using getHours(). The expected output should be 2am. Could there be an error in my code? I have highlighted the problematic section ...

Image Handpicked by JCrop User

Successfully implemented JCrop example code for selecting an area on an image with a preview and getting coordinates. However, the challenge lies in allowing users to select an image from their file system, display it in the browser, and perform the afore ...

Toggling between different divisions independently

I'm trying to create a navigation bar similar to Twitter. I want one specific div within the bar to scroll with notifications or news, while keeping the rest of the bar content unchanged. Any ideas on how to achieve this? Check out my code here. #nav ...

what is the best method to locate a parent element containing a particular child using By.xpath()?

In the past few days, I've been utilizing the selenium-webdriver in nodejs for web scraping. However, I am facing an issue on how to locate an element that contains a specific child element. I have attempted to use the following operator but it does ...

Error message indicating a problem with the locator By.linkText that contains dots in Selenium: TypeError - Invalid locator

I've searched through other resources for solutions, but I can't find anything that addresses my specific issue. The error message I'm encountering is TypeError: Invalid locator. Here's a snippet of my code (where I suspect the problem ...

Obtain an individual item from the reducer array

I am working on a company reducer that will store an array of companies. To optimize performance, I aim to fetch only the necessary company object from my API when a user navigates to /company/name. This way, if a user visits the same company page multiple ...

Different method for adding child elements to the DOM

When creating a DOM element, I am following this process: var imgEle = document.createElement('img');     imgEle.src = imgURL;             x.appendChild(imgEle); Instead of appending the last line which creates multiple img elements ev ...

Ways to retrieve environmental setups from nx workspace with express

Within my nx-workspace, I have encountered a scenario where there are 2 separate environment.ts files named environment.ts and environment.prod.ts. I am currently facing an issue with retrieving the base url from the environment.ts file, which corresponds ...

Using Ubuntu, AWS EC2 Instance unable to start Node.JS Express App

For the past 24 hours, I have been struggling to get my express app up and running. Despite following tutorials and reinstalling everything, I still can't seem to make it work. If you're curious about the M.E.A.N stack installation process that ...

Find one record for each unique serial number in MongoDB

There are four documents in my possession, each bearing a unique serial number. My objective is to retrieve the final document associated with each serial number. For instance. Collect Name:Sales Serial name date 10000 A 2014 10000 B 2015 ...

Is it possible to utilize npm packages within a standard web page without any frameworks or libraries?

I am currently working on a basic website created using vanilla HTML, CSS, and JS files. My goal is to incorporate the import { moment } from "moment" syntax into my JS files. However, after adding npm to my project, installing moment with npm i ...

Use Puppeteer and Node.js to repeatedly click a button until it is no longer present, then initiate the next step

Imagine a dynamic web page filled with rows of constantly updated data. The number of rows on the page remains fixed, meaning old rows are replaced and not stored anywhere. To navigate through this page, you need to click on a "load more" button that app ...

Show information from a JSON file in a tooltip on a Highcharts' pie chart

I have a pie chart that shows two percentages. I am looking to update the tooltip content to display information from my JSON data. Here is an example of how my JSON data looks: {"object1":{"percentage": 0.7, "numberOfObject": 167}, "object2":{"percentage ...

Looking for ways to locate encoded HTML values in chrome?

Referenced from Microsoft Docs In MVC, the Razor engine automatically encodes all output coming from variables. For example, consider the following razor view: @{ var untrustedInput = "<"123">"; } @untrustedInput In this scenario, ...

Creating variables in styled-components allows you to easily reuse values throughout

Can a variable be defined inside a styled-components component? The code snippet below, although not functioning properly, demonstrates my intention: const Example = styled.div` ${const length = calc(vw - props.someValue)} width: ${length}; &. ...

Preventing preventDefault() from firing in JQuery only when necessary

I have come up with a script that I recently created. <script> $(document).ready(function(){ $('a').data('loop',true); $('body').on('click', 'a', function(event){ console.lo ...

Tips on how to update the styling of an active link

http://jsfiddle.net/G8djC/2/ Looking to create a tabbed area where content changes based on the tab clicked. The Javascript function switches the link class to active upon clicking. However, struggling to change the color of the active tab beyond the firs ...

Images with spaces in their names are failing to load in React Native

I am currently trying to utilize an image within my react native application. At this point, my code is very minimal. The following code snippet is all I have for now: import React from 'react'; import { ScrollView, View, Text } from 'reac ...

Enhancing HTML through Angular 7 with HTTP responses

Sorry to bother you with this question, but I could really use some help. I'm facing an issue with updating the innerHTML or text of a specific HTML div based on data from an observable. When I try to access the element's content using .innerHTM ...