How come my countdown application functions properly when accessed through the browser via the HTML page, but encounters issues when utilized with an HTTP server?

I have encountered an issue where the app functions correctly when I open the HTML file in my browser, but fails to load the CSS and JavaScript when accessing it through localhost:3000.

HTML:

<html>
  <head>
<link href="./main.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <div id="del-countdown">
     <h1>THE SINGULARITY IS NEAR</h1>
     <div id="clock"></div>
      <div id="units">
       <span>Years</span>
       <span>Days</span>
       <span>Hours</span>
       <span>Minutes</span>
       <span>Seconds</span>
      </div>
    </div>
  <script src="../index.js"></script>
 </body>
</html>

CSS:

body{
  background: #282e3a;
  font-family: tahoma;
}
h1{
  color: #fff;
  text-align: center;
  font-size: 74px;
  letter-spacing: 10px;
  margin-bottom: 5px;
}
h3{
  color: #fff;
  text-align: center;
  font-size: 36px;
  letter-spacing: 5px;
  margin-top: 5px;
}
#del-countdown{
  width: 850px;
  margin: 15% auto;
}
#clock span{
  float: left;
  text-align: center;
  font-size: 84px;
  margin: 0 2%;
  color: #fff;
  padding: 20px;
  width: 16%;
  border-radius: 20px;
  box-sizing: border-box;
}
#clock span:nth-child(1){
  background: #696868;
}
#clock span:nth-child(2){
  background: #7D7C7C;
}
#clock span:nth-child(3){
  background: #9E9E9E;
}
#clock span:nth-child(4){
  background: #C4C4C4;
}
#clock span:nth-child(5){
  background: #D9D7D7;
}
#clock:after{
  content: "";
  display: block;
  clear: both;
}
#units span{
  float: left;
  width: 20%;
  text-align: center;
  margin-top: 30px;
  color: #ddd;
  text-transform: uppercase;
  font-size: 13px;
  letter-spacing: 2px;
  text-shadow: 1px 1px 1px rgba(10,10,10, 0.7);
}

span.turn{
  animation: turn 0.7s ease forwards;
}

@keyframes turn{
  0%{transform: rotateX(0deg)}
  100%{transform: rotateX(360deg)}
}

Index.js:

function updateTimer(deadline){
  var time = deadline - new Date();
  return {
    'years': Math.floor( time/(1000*60*60*24*365) ),
    'days': Math.floor( time/(1000*60*60*24) % 365 ),
    'hours': Math.floor( (time/(1000*60*60)) % 24 ),
    'minutes': Math.floor( (time/1000/60) % 60 ),
    'seconds': Math.floor( (time/1000) % 60 ),
    'total' : time
  };
}


function animateClock(span){
  span.className = "turn";
  setTimeout(function(){
    span.className = "";
  },700);
}

function startTimer(id, deadline){
  var timerInterval = setInterval(function(){
    var clock = document.getElementById(id);
    var timer = updateTimer(deadline);

    clock.innerHTML = '<span>' + timer.years + '</span>'
                    + '<span>' + timer.days + '</span>'
                    + '<span>' + timer.hours + '</span>'
                    + '<span>' + timer.minutes + '</span>'
                    + '<span>' + timer.seconds + '</span>';

    //animations
    var spans = clock.getElementsByTagName("span");
    animateClock(spans[4]);
    if(timer.seconds == 59) animateClock(spans[3]);
    if(timer.minutes == 59 && timer.seconds == 59) animateClock(spans[2]);
    if(timer.hours == 23 && timer.minutes == 59 && timer.seconds == 59) animateClock(spans[1]);
    if(timer.days == 364 && timer.hours == 23 && timer.minutes == 59 && timer.seconds == 59) animateClock(spans[0]);

    //check for end of timer
    if(timer.total < 1){
      clearInterval(timerInterval);
      clock.innerHTML = '<span>0</span><span>0</span><span>0</span><span>0</span><span>0</span>';
    }


  }, 1000);
}


window.onload = function(){
  var deadline = new Date("January 01, 2045 00:00:01");
  startTimer("clock", deadline);
};

Server.js

var http = require('http')
var fs = require('fs')
var path = require('path')

//404 response
function send404Response(res) {
  res.writeHead(404, {"Content-Type": "text/plain"})
  res.write("Error 404: Page not found!")
  res.end()
}

//Handle user request
function onRequest(req, res) {
  if(req.method == 'GET' && req.url == '/') {
    res.writeHead(200, {"Content-Type": "text/html"})
    fs.createReadStream("./public/index.html").pipe(res)
  }
  else{
    send404Response(res)
  }
}

http.createServer(onRequest).listen(3000)
console.log("The server is now up and running...");

Answer №1

Make sure to organize your JavaScript and CSS files in a directory labeled "public." Then, include the following line of code:

app.use('/public',express.static(__dirname + '/public'));
Next, link to your CSS and JavaScript files like this: src="/public/js"

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

Request to api.upcitemdb.com endpoint encountering CORS issue

This code may seem simple, but for some reason, it's not working as expected. What I'm trying to achieve is to call the GET API at: I want to make this API call using either JavaScript or jQuery. I've attempted various approaches, but none ...

Issue with Ajax form submission functionality not working for sending form data

I recently found the solution to executing a Send Mail script without reloading the page after facing some AJAX issues. However, I am now encountering a problem where the post data is not being received by the PHP script when my form posts to AJAX. For re ...

When a global variable is defined after a return statement within a function declaration, it does

Check out this Javascript code snippet: http://jsfiddle.net/ramchiranjeevi/63uML/ var foo = 1; function bar() { foo = 10; return; function foo() {} } bar(); console.log(foo); // should return 10, but returns 1 It's interesting to no ...

Can you explain the functionality of this JavaScript registration code?

I am working on an ajax/jquery 1.3.2 based sign up form and I am looking to gain a deeper understanding of how to incorporate jquery into my projects by analyzing the code line by line. Could someone provide a detailed explanation of this code and break d ...

Adjust the width of the <li> element based on the quantity of its children

If the number of list items can be changed dynamically, how can I adjust the width of each item so that the total width is always 100%? Here is an example code snippet: <nav> <ul> <li>A</li> <li>B</li> &l ...

Should servlet response be HTML for use in AJAX calls?

I am currently in the process of developing a web application with multiple pages, including index.html which serves as the main page and contains various <a> tabs linking to different Servlet pages. As part of my design, I have a consistent CSS lay ...

What is the best way to calculate the total duration (hh:mm) of all TR elements using jQuery?

I currently have 3 input fields. The first input field contains the start time, the second input field contains the end time, and the third input field contains the duration between the start and end times in HH:mm format. My goal is to sum up all the dur ...

Updating ng-table within an Angular controller

Having encountered an unusual issue with ng-table. Here is a snippet of code from my controller: this.category = "Open"; this.category = ["Open", "Accepted", "Rejected"]; this.dataItems = []; var _this = this; this.$scope.$watch("vm.category", function( ...

Hide the menu when tapping outside on a tablet device

Currently working with HTML, CSS, and JS (specifically Angular) I have a Header menu that contains dropdown sub-menus and sub-sub-menus in desktop view. On a PC, the sub-menus appear on hover and clicking on an entry redirects you somewhere. Clicking o ...

Ways to resolve eslint typedef error when using angular reactive forms with form.value

I am facing an issue with my formGroup and how I initialized it. Whenever I try to retrieve the complete form value using form.value, I encounter an eslint error related to typecasting. userForm = new FormGroup<user>({ name: new FormControl<st ...

How come only the individual top, bottom, left and right paddings function correctly while the combined padding does not respond?

Seeking to customize a button using SCSS file that is connected to HTML. This button is part of a flex layout design. The element's size is set at 83.333×16px. The box-sizing property is defined as: box-sizing: border-box; Adding padding with s ...

Difficulty encountered when attempting to toggle visibility of div elements in Internet Explorer version 10

Working on my .aspx webpage, I have a set of div tags that play a key role in the layout. Let me show you an example with the following snippet: <div id="homeownerquestion" runat="server"> Are you the property owner? <p> <asp:RadioButto ...

Looking for a way to manipulate the items in my cart by adding, removing, increasing quantity, and adjusting prices accordingly. Created by Telmo

I am currently working on enhancing telmo sampiao's shopping cart series code by adding functionality for removing items and implementing increment/decrement buttons, all while incorporating local storage to store the data. function displayCart(){ ...

How can I change the Safari blue outline to black?

I have an input field and I have applied the following CSS to it: input:active, input:focus { outline: 1px auto rgb(16, 16, 16) !important; outline-offset:0px; } However, when I tested it using , the input field still had a blue outline: I was hoping ...

Obtain the data of the highlighted row in a telerik grid directly from the client side

I am attempting to retrieve the value of a GridBoundColumn with DataField="id" using JavaScript on the client side. When the user clicks on the image button within a row, I need to extract the id for that specific row and then invoke a web method by passin ...

Error opening file in the browser Firefox://///

I have data displaying detailed information in a table. Within the table, there is a link that points to my local IP address \\192.168.182.23 The source URL for the link looks like this: <a target="_blank" href="file://///192.168.182.23/dt/r ...

Testing actual HTTP requests in unit and integration tests with AngularJS

Attempting a request that was not mocked using $httpBackend.when in an Angular 1.x unit/integration test will lead to an error: Error: Unexpected request: GET /real-request Is there a way to perform actual HTTP requests with ngMock and the Karma+Jasmin ...

Combining server-side and client-side routing in AngularJS: A comprehensive guide

Currently, I am in the process of transitioning a project to an Angular-based Single Page Application (SPA). The project is originally built using node/locomotivejs and serves templates from the server side. Due to its large size, we are converting it to A ...

Mastering image focus with javascript: A comprehensive guide

On my HTML page, I have two images and a textbox. I want the focus to shift between the images based on the first character entered in the textbox. For example, when the user types '3', the first image should be focused, and for '4', th ...

Issues with HTML rendering text

Having trouble with text display on my website. It seems to vary based on screen resolution, but I can't figure out why. Any insights on what might be causing this issue? Check out the source code here <body> <div id="navwrap"> < ...