Loading an empty CSS file in Node.js

Just starting out with node.js, and I could really use some help with a small css and image issue that I'm facing. I've streamlined my html and .js for clarity. Despite trying everything, the css and image just won't load. My form and server are all functioning correctly, it's just these two elements giving me trouble. Any assistance would be greatly appreciated!

file structure

webDemo
node_modules
public
   css
     indexCss.css
   images
      powerbyfhirlogo.JPG
index.html
package.json
server.js

main part of my node file.

var http = require('http');
var fs = require('fs');
var path = require('path');
var formidable = require("formidable");
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
var request = require("request");
var express = require('express');
var app = express();
var server = http.createServer(function (req, res) {

if (req.method.toLowerCase() == 'get') {
    app.use(express.static(path.join(__dirname, '/public')));
    displayForm(res);
}
else if (req.method.toLowerCase() == 'post') {

    processFormFieldsIndividual(req, res);
  }
});

function displayForm(res) {


    fs.readFile('index.html', function (err, data) {
    res.writeHead(200, {
        'Content-Type': 'text/html',
        'Content-Length': data.length
    });

    res.write(data);
    res.end();
});
}

server.listen(63342);
console.log("server listening on 63342");

beginning of my html file.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>MI FHIR Demo Form</title>
<link rel="stylesheet" type="text/css" href="public/css/indexCss.css" />

</head>
 <body>
<div class=container1>
    <img src= "public/images/powerbyfhirlogo.JPG" class="img-rounded" alt="Cinque Terre">
    <h1>MI FHIR Demo Form</h1>
</div>
<hr/>

<div class=container2>
    <form role="form" action="" method="post" enctype="multipart/form-data">

Edit solution

var express = require('express');
var path = require('path');
var server = express();

var port = process.env.port || 63342;

// Setup Views & View Engine
server.set('views', path.join(__dirname, 'views'));
server.engine('html', require('ejs').renderFile);
server.set('view engine', 'html');


// Define ./public as static
server.use(express.static(path.join(__dirname, 'public')));

//All POST's use processFormFieldsIndividual
server.post('*', processFormFieldsIndividual);

server.listen(port, function() {
    console.log('listening on port ' + port);
});

new file structure

webDemo
   node_modules
   public
      css
        indexCss.css
      images
         powerbyfhirlogo.JPG
      index.html
   package.json
   server.js

Answer №1

Using two different servers in your server file, app and server, is not recommended as they are not interchangeable. It's best to stick with one server for consistency.

If you are using express, there is no need for http.createServer() since express already functions as a Node Core http server.

It is also unnecessary to redeclare static files for every single GET request.

Here is a simplified version of what you need:

var express = require('express');
var path = require('path');
var server = express();

var port = process.env.port || 63342;

// Setup Views & View Engine
server.set('views', path.join(__dirname, 'views'));
server.engine('html', require('ejs').renderFile);
server.set('view engine', 'html');

// Define ./public as static
server.use(express.static(path.join(__dirname, 'public')));

//All GET's render index.html
server.get('*', function(req, res) {
    return res.render('index');
});  

//All POST's use processFormFieldsIndividual
server.post('*', processFormFieldsIndividual);

server.listen(port, function() {
    console.log('listening on port ' + port);
});

EDIT

To simplify the code and eliminate the use of res.sendFile(), I have integrated a view engine using ejs. You will need to install ejs as a dependency through npm.

npm i --save ejs

Ensure that your index.html is placed in a new directory named views within your project folder. This setup allows you to utilize res.render instead of res.sendFile(). Your new directory structure should resemble the one below.

webDemo
node_modules
public
   css
     indexCss.css
   images
      powerbyfhirlogo.JPG
views
   index.html
package.json
server.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

Troubleshooting the Height Problem in Material-UI's Menu

I am trying to make the menu height responsive by setting it equal to the window height using CSS. I want the menu height to increase as the page length increases due to added elements. I have attempted using "height:100%" and "height: 100vh" in the styles ...

The use of event.returnValue is outdated and no longer supported. It is recommended to use the standard event.preventDefault() method instead. You may encounter

Hey there :) Currently, I am utilizing JQuery 1.9.1.js to search records using JSON. I am able to retrieve the search list locally, but when attempting to publish it on Windows Server 2008 and IIS 7, I face issues as it throws an error stating "event.ret ...

Exploring the ways to connect to different MongoDB databases using Node.js

Can someone assist me with this inquiry? I am attempting to create a node express REST API that needs to work with multiple MongoDB databases on the same MongoDB server. What is the best approach to achieve this? The steps could be: app starts connect ...

Is it possible to determine if NPM install is functioning correctly in various situations or does it vary?

npm init is the first step to start a project I have specified axios: "~1.2.4" in my package.json file When I execute npm install, it installs version 1.2.6, updating to the latest patch as expected If I use ^1.2.4 in package.json and run npm in ...

Ways to dynamically emphasize text within ngFor loop

Within my ngFor loop, I have a set of rows. <div *ngFor="let block of data;"> <div class="class-row"> <div class="left">A Label:</div> <div class="right">{{block.key1}}</div> </div> <div class="clas ...

store the id of each li element dynamically into an array

In my code, a list is generated dynamically and each list item has a special id. I am trying to store each li "id" in one array. This is JavaScript code: var i = 0; $("ul#portfolio li").each(function(eval) { var idd = new Array(); idd[i] = $(this ...

Is there a way to extract text from a span element using selenium?

Below is my current code implementation: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time as t P ...

What is causing the ESLint error when trying to use an async function that returns a Promise?

In my Next.js application, I have defined an async function with Promise return and used it as an event handler for an HTML anchor element. However, when I try to run my code, ESLint throws the following error: "Promise-returning function provided t ...

Managing iframe scrolling using the parent window's scrollbar

I am currently working on an iframe to be utilized across various domains. The functionality of this iframe involves displaying a data list that updates when the bottom of the scroll is reached. An issue I encountered is that the parent window, where the ...

Problems encountered with nested AJAX calls and the $.when.apply function handling deferred promises efficiently

I am attempting to create a triple nested series of AJAX calls, as shown in the basic structure below (fail calls have been omitted). Progress is being made up to the second level with the eventCalls. The final when.apply.done only triggers after every si ...

Unable to align element to the left due to the position being below

<ul class="unlist clearfix"> <li class="clearfix"> <h3>List Item</h3> <time datetime="2013-08-29"><span>29</span> Ags 2013</time> </li> ...

Troubleshooting Angular 2 Fallback Route Failure

My current project is using Angular 2 Webpack Starter but I am having trouble with the fallback route. In my app.routes.ts file, I have defined the routes as follows: import { Routes } from '@angular/router'; import { HomeComponent } from &apos ...

Difficulty in toggling the visibility of the react-date-range picker package when selecting a date

I need assistance with a problem I'm facing. I am having trouble hiding and showing the react-date-range picker upon date selection. The issue is related to a package that I am using for date range selection. You can find the package link here - https ...

Ensure that the content inside the centrally aligned div is also aligned at the

Looking for a way to center a box on a website I'm designing? Instead of aligning it based on existing centering, use the following HTML / CSS code to ensure that the white box is perfectly centered on the page. .loading { position: fixed; z-in ...

Inside the function() in angular 2, the value of 'this' is not defined

I've integrated a UIkit confirmation modal into my app. However, I'm encountering an issue when trying to click the <button> for confirmation. The this inside the function is showing up as undefined. Here's the snippet of code in quest ...

Simulate/Assess MongoDB Database with Node.js

Currently diving into the world of nodejs and navigating a mongodb database. Considering mocha for unit testing and zombie.js for acceptance testing, but curious about how to conduct full-scale acceptance tests that involve interacting with the mongodb dat ...

The top navigation menu is positioned above the sidebar menu due to a CSS error

Having an issue with adding top and side menus. The top menu is displaying above the side menu. Can someone help fix the css? Here is my fiddle. I attempted to apply #leftPanel position:fixed but it did not work as expected. ...

Retrieve the properties of an object

I have a JavaScript program where I retrieve values from a JSON file and store them in an array. However, when I attempt to access the elements of this array, it returns nothing. Below is the function that pushes temperatures: temperatures = [] get_info ...

Verify if any choices are available before displaying the div block

I need to determine if there is a specific option selected in a dropdown menu, and then display a div if the option exists, otherwise hide it. I'm not just checking the currently selected option, but all available options. if (jQuery(".sd select opti ...

Refreshing Slickgrid: Updating grid data with data fetched from an AJAX source

Within the app I am developing, there exists a data grid alongside select boxes that allow users to set filters. Upon selection of these filters, an AJAX call is made to retrieve a new array of data from the server. The challenge I currently face is wipin ...