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

What is the best way to pass an asynchronous database query result from one Node.js module to another?

I'm currently learning Node.js and I've been exploring a pattern from an online API course. The approach involves using route, controller, and service modules to organize the flow of data. The database queries are handled within the service modul ...

Angular8 Chart.js customizes the Y axis tick labels

Is there a way to dynamically adjust the Y-axis ticks in a chart.js graph? I attempted to modify them using the following commands: this.chartOptions.scales.yAxes[0].ticks.min = 10; this.chartOptions.scales.yAxes[0].ticks.max = 18; ...

Every time I reload the page, a new row is added to the database

When I attempt to refresh the page, a new row appears each time. Trying to troubleshoot this issue has been challenging for me as I am still relatively new to database programming. The source of the repeated value is unclear to me, as it continues to show ...

Problem with setting headers in Express Async: Is a double callback causing headers to be sent twice?

I've encountered a frustrating issue with 'Error: Can't set headers after they are sent.' in my Express code. This problem arose after switching from Restify to Express, and despite making necessary adjustments, the error persists. The ...

Troubleshooting the "Request failed with status code 500" error when refreshing a page in a React application

Every time the page is reloaded, an error message pops up saying: Uncaught (in promise) Error: Request failed with status code 500. Here's the code in list.tsx: const [state, setState] = useState([]); const { getRoom } = useRoom(); const fe ...

Processing hover attributes in Tailwind-styled-components

I'm currently working on a website that features a dark mode, and I want to utilize the dark prop in tailwind-styled-components. The props work fine in all instances except for actions like hover, active, focus, etc. When attempting to use hover and t ...

The functionality of ng-style is not compatible with min, and utilizing ng-model produces undesirable results

Why does the ng-style condition not work with min=0 if the saved value of ng-model="detail.Amount" is negative? <input type="number" min="0" oninput="validity.valid||(value='');" class="form-control" title="Amount" ng-model="detail.Amount" ng ...

Ways to insert a line break within a jQuery function using text()

I am looking to add a new line in my jQuery function. $.ajax({ url:"http: //192.168.1.4/Experiements/webservices/api.php", type:"GET", dataType:"json", data:{type:"login", UserName:userId,Password:userPassword}, ...

How can I use jQuery to target and modify multiple elements simultaneously

I've been struggling for the past couple of hours trying to use prop to change the values of two items in a button. One item updates successfully, but the other one doesn't and I can't figure out why. Here is the HTML: <input type=&apos ...

Utilize React-select in Nextjs to dynamically alter URLs through options

During my attempt to implement react-select for changing the URL based on user-selected multiple options to filter numbers, I encountered a challenge. When using multiple options, the URL changes successfully to fetch data, as seen in this example: https:/ ...

Pressing the non-responsive button automatically chooses the following item

This example demonstrates how to create a disabled button: import { Grid, IconButton } from "@material-ui/core"; import ArrowBackIosIcon from "@material-ui/icons/ArrowBackIos"; export default function App() { const handleClick = (e) ...

Adjust Fabric js Canvas Size to Fill Entire Screen

Currently, I am working with version 4.3.1 of the Fabric js library and my goal is to adjust the canvas area to fit its parent div #contCanvasLogo. I have tried multiple approaches without success as the canvas continues to resize on its own. Below is the ...

Docker deployment unsuccessful: Module 'heroku' not located in app directory

I have set up a Node application in Docker that I am looking to deploy on Heroku using the deploy GitHub action found here: https://github.com/AkhileshNS/heroku-deploy/tree/master The app has already been created on Heroku and is currently using the defau ...

Dealing with unreadable strings when formatting dates in a JSP

When working on a JSP project, I encountered a situation where I needed to format a Java Date retrieved from the request. My current approach looks like this: <fmt:formatDate value="${attribute.value}" pattern="yyyy-MM-dd HH:mm:ss"/> This method wo ...

Highlight the nearest nodes using visNetwork, displaying only the edges that are connected to the selected node

Currently, I am analyzing a Twitter network that consists of United States senators. My goal is to have the ability to choose a specific senator (using nodeIdSelection) and highlight only the nodes connected to that selected senator along with highlighting ...

JavaScript must be able to detect when the checkbox value is reversed, which is dependent on the user-entered data

Hey there, I come across a situation where users are selecting a checkbox to insert or update a row of data in a MySQL database through SparkJava/ Java. The functionality is working fine except for a minor glitch. The issue arises when the checkbox behav ...

JavaScript error - Property value is not valid

When I use IE 6/7/8, I encounter a JavaScript error message. The problematic line of code reads as follows: document.getElementById('all').style.backgroundColor = color; The specific error reported in IE 6/7/8 is as follows: Invalid property ...

Map on leaflet not showing up

I followed the tutorial at http://leafletjs.com/examples/quick-start/ as instructed. After downloading the css and js files to my local directory, I expected to see a map but all I get is a gray background. Can anyone advise me on what might be missing? T ...

Troubleshooting problem with table reflow in Bootstrap v4.0.0-alpha.3 on mobile devices

I am having trouble fixing the table-reflow issue in mobile view while trying out the code below. Any suggestions on how to resolve this would be greatly appreciated. Check out the image here To see the code, visit CODEPEN <div class="container"> ...

What is the best way to create a loop with JSON data?

My challenge is to showcase json data using a loop. I have received the following results, but I am unsure of how to display them with a loop. [ {"latitude":"23.046100780353495","longitude":"72.56860542227514"}, {"latitude":"23.088427701737665"," ...