Unable to fetch css file in Node.js

I am currently in the process of learning Node.js, but I have encountered a small issue with retrieving data from a css file. Interestingly, when I directly add the data to the index file's code, it seems to work perfectly.

Let me share the relevant snippets of my code:

app.js

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

//404 response

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

function onRequest(request, response) {
  if (request.method == 'GET' && request.url == '/') {
    response.writeHead(200, {
      "Context-Type": "text/html"
    });
    fs.createReadStream("./index.html").pipe(response);
  } else {
    send404response(response);
  }
}

http.createServer(onRequest).listen(8888);
console

index.html

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8>
    <link rel="stylesheet" type="text/css" href="main.css" >
    <title>First node app</title>
</head>
<body>
<div class="header"></div>
<div class="container">Welcome to my first website! <br> This website is  created in NodeJs!</div>
</body>
</html>

main.css

* {
  margin: 0px;
  padding: 0px;
}

body {
  background: url('https://i.sstatic.net/1voHP.png') repeat;
  font-size: 100%;
}

.header {
  width: 100%;
  height: 500px;
  background: rgba(0, 0, 0, .9);
}

.container {
  font-size: 1em;
  margin: 0 auto;
  width: 70%;
  height: 90%;
  background: rgba(0, 0, 0, .3);
  padding: 5%;
}

* {
  margin: 0px;
  padding: 0px;
}

body {
  background: url('https://i.sstatic.net/1voHP.png') repeat;
  font-size: 100%;
}

.header {
  width: 100%;
  height: 500px;
  background: rgba(0, 0, 0, .9);
}

.container {
  font-size: 1em;
  margin: 0 auto;
  width: 70%;
  height: 90%;
  background: rgba(0, 0, 0, .3);
  padding: 5%;
}

All these files are stored in the same directory.

Answer №1

if( request.method == 'GET' && request.url == '/' ){
    response.writeHead(200, {"Context-Type": "text/html"});
    fs.createReadStream("./index.html").pipe(response);

When the browser requests /, the homepage will be sent to them.

}else{
    send404response(response);

If anything else is requested by the browser, a 404 error will be sent.

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

If the browser asks for /main.css, a 404 error will be returned.

A specific code needs to be implemented to handle the scenario where the browser requests /main.css.

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

The footer is supposed to be at the bottom, but unfortunately, the clear float isn

Today seems to be a rough one without enough coffee, as I'm struggling to remember how to do this I am trying to achieve the following layout: header content float float footer The content section contains two floating elements. The problem is ...

Manipulating Arrays in JavaScript: Techniques for Extracting Values Buried in Nested Objects

I am working with an array of objects that contain multiple "Book" objects with dynamic keys. My goal is to filter the objects in the array to only include those that have at least one new "Book" object. For example: const arr = [ { id: '123&ap ...

Violation of Content Security Policy directive has occurred

During my full-stack project development, I encountered an issue with the inclusion of the bundle.js file in my base HTML file using a simple script tag. When trying to render the page and utilize the JS functionality, I faced a content security policy vio ...

Ways to eliminate excessive spacing between grid blocks

Hey, I'm having an issue with displaying ads in a thumbnail format; there seems to be too much space between them. Take a look: I've been utilizing Bootstrap thumbnails to showcase products. echo '<div class="col-sm-6 co ...

Utilize page variables to activate audio clips upon clicking

Can someone assist me with a script that activates an audio clip when five icons on a page are clicked? The image of the icons can be found below: https://i.stack.imgur.com/mBC6o.png Here is the HTML code: <div class="slide overlay-container" id="int ...

Trigger an Angular2 component function from an HTML element by simply clicking a button

I'm just starting out with TypeScript and Angular2 and encountering an issue when trying to call a component function by clicking on an HTML button. When I use the **onclick="locateHotelOnMap()"** attribute on the HTML button element, I receive this ...

Utilizing npm packages with grunt: A guide

Initially, when I was working with node.js without grunt, I simply had to write the code below to import an external module. var express = require('express'); However, after transitioning to grunt, I attempted to utilize the qr-image module in ...

Error in Firebase cloud functions: The reference to the child is invalid. Please check the path provided as the first argument

I'm currently working on implementing push notifications by following this tutorial: https://www.youtube.com/watch?v=z27IroVNFLI Although the tutorial is a bit dated, there aren't many viable alternatives for Firebase web apps. When my cloud fu ...

Issue with showing multiple images on HTML page

I'm currently working on enhancing my webpage by enabling the upload of multiple images. However, I'm facing challenges in figuring out how to obtain a valid URL for the image source and to verify if the correct number of files have been uploaded ...

Setting up a secure HTTPS server using Node.js and Express.js

Currently in the process of setting up a HTTPS server using Node.js and Express.js. This is what I have so far: const filesystem = require('fs'); const express = require('express'); const server = express(); const http = require(&apos ...

Launching the Node.js application on Heroku resulted in encountering an issue: "Application error - There was a problem within the application

When I access the browser using http://localhost:8080/, I can see the message Hello World with Express. I am currently trying to deploy this application on Heroku. I have followed the tutorial provided by Heroku. 1) Create a new app 2) Choose an App name ...

Transfer the updated variable from a static JavaScript file to Next.js

I am facing a challenge with a conditional render in my component. I am unable to display the value of a variable. In one file, I have all my functions that I export in index.js import FunctionServices from "../services/functionServices" export ...

The Node.Js application encounters an EADDRINUSE error upon being restarted

My question may seem repetitive, but please read it in its entirety before marking it as a duplicate or anything else. I've been learning node.js to create a rest API and have been making great progress. Everything was running smoothly until I encoun ...

PHP: Create a list of checkboxes and submit them via form

Following a SQL query, I receive a form displaying a list of data, each line accompanied by checkboxes. The purpose is to allow users to select certain lines for deletion from the database upon form submission. In order to identify which lines are selecte ...

Creating a Navigation Bar using the Flexbox property

As a beginner, I attempted to create a navbar using flex but did not achieve the desired outcome. My goal is to have: Logo Home About Services Contact * { margin: 0; padding: 0; font-family: ...

AJAX issue: "Content-Type header is missing the multipart boundary parameter"

Currently, I am encountering an issue while attempting to transfer a file from localhost to a server. The error message displayed in my network console is as follows, with status code 500: "no multipart boundary param in Content-Type" To address this p ...

The password generated refuses to be saved

I've encountered an issue with saving a hashed password. Previously, when I saved the password as it was, everything worked fine. However, after implementing bcrypt for encryption, the process no longer works. The JSON response no longer includes the ...

Struggling to download giveaway-grabber, encountering an error message stating that the operating system has denied the operation

Having trouble installing a script for running Amazon giveaways. I've downloaded node.js but keep getting "permission denied" when trying to install giveaway-grabber on MacOS. Tried using sudo, but still unsuccessful. Looking for some guidance on the ...

Transfer the textbox value from page-1 to page-2 seamlessly with the help of AngularJS UI-routing

I'm attempting to transfer the textbox value from Page-1 to Page-2 using the code below, but I am encountering difficulties. Page-1.html <div > <div style="height: 400px"> <h2>Partial view-1</h2> <p> ...

Incorporate external JavaScript libraries not built with Angular

Our project utilizes NPM in conjunction with Browserify for managing third-party dependencies, which pairs well with AngularJS due to the CommonJS-modules. Below is a code snippet showcasing the dependency structure that integrates seamlessly with Angular ...