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

Asynchronous retrieval of reference value from Firebase Firestore in ReactJS

Encountering a peculiar bug in TypeScript-JavaScript where I have a Model class in TypeScript and a ReactJS Component in JS. The issue arises when dealing with a list of Promo Objects, each containing a "_listCompte" property which holds a list of Compte O ...

unable to load the ajax file

While setting up Ajax, I encountered an error message in IE that reads: Description: An issue occurred during the processing of a configuration file needed to handle this request. Please check the specific error details below and adjust your configuration ...

Picking out specific SharePoint components using jQuery

I encountered an issue with making my two radio boxes readonly. To resolve this, I attempted to disable the unchecked option. Despite trying to access the elements using jQuery and reviewing the data from the console, the solution did not work as expected. ...

Could not locate a local gulp installation

Regarding the situation described in this inquiry, I have executed sudo npm install gulp -g and npm install gulp --save-dev. However, despite my efforts, I continue to encounter a persistent issue. Gulp seems unable to detect the local node_modules/.bin/gu ...

invoke two JavaScript functions without displaying any message

I'm facing an issue with Ajax as it's not displaying the message I intend to show. Let me elaborate. Within my PHP code, there is an input tag: <input type="submit" id="login_button_add" name="submit" value="Add" onclick="add_building(); sho ...

Align a header and a block of text in a vertical manner within a div

Struggling to align a h1 element and p vertically in the middle of a left-floated div, but they end up next to each other aligned vertically. Seems like table-cell display is the culprit, but not sure how to achieve vertical alignment without it. The curr ...

How to center an image within a div without it moving

I have set up a JSFiddle for reference: http://jsfiddle.net/AsHW6/ My task involves centering the down_arrow.png images within their respective div containers. I have successfully centered the up_arrow.png images using auto margins. These images are posit ...

Encountering a hiccup as I attempt to set up a new user through Express NodeJs with Passport integration

I'm encountering an issue while attempting to set up a registration page for users. After trying to make a POST request to save the user in the database, I am getting an error that states TypeError: req.checkBody is not a function. I have also used np ...

Offering various language options on a website determined by the URL

I've been contemplating how to add multi-language support to my personal website, which I developed using ExpressJS and NodeJS with EJS as the template engine. Currently, the website is only available in English, but I want to add a German version as ...

What is the correct way to configure environment variables in a Next.js application deployed on Vercel?

As I develop my web app in Next.js, I have been conducting tests to ensure its functionality. Currently, my process involves pushing the code to GitHub and deploying the project on Vercel. Incorporating Google APIs dependencies required me to obtain a Cli ...

Incorporating Auth0 into a Node.js and Express application

In my mobile app built with Flutter, I am utilizing Node and Express for the backend. For all authentication REST functionality facing the client, I want to implement auth0's services. They are experts in handling security threats better than I can o ...

Providing structured Express app to deliver HTML and JavaScript content

Currently, I am working with Express and facing a seemingly simple challenge. Here is the structure of my directories: |-config |---config.js |---routes.js |-server.js |-scripts |---controllers |------controllers.js |---directive ...

Guide on integrating a JavaScript control (JavaScript package) obtained from GitHub into my asp.net application

Hello everyone, I am a newcomer to GitHub and have some basic questions to ask. Recently, I downloaded the package from https://github.com/jspreadsheet/ce in .zip format for using in my asp.net web application. However, I am not sure how to incorporate the ...

Minimize the amount of external asynchronous calls made by the client

In my application, the client initiates multiple asynchronous JavaScript requests to third party servers. The issue I'm encountering is that when the client responds to these requests, the site becomes inactive for a brief period of time. This inactiv ...

Issue with res.format.html not functioning properly in conjunction with the paginate module

I've encountered a problem while using the express-paginate module in my project. The issue seems to be related to the res.format section within my routes file, as it's causing the paginate function to not be found when rendering the view file. ...

Is it possible to define a multiplication margin using css?

I am trying to place a box in the center of a container, but I am unable to set a static height for the parent element as it may change. This is causing issues with aligning the box perfectly in the middle of the page. Any assistance would be greatly app ...

utilizing the target attribute within a form to open the link in the current page

I have been working on a web application and implemented a drop-down menu using a form to display information about the selected category. However, I noticed that when an option is selected, the link opens in a new window instead of the same window. Below ...

Exploring JSON Data with NativeScript

As a newcomer to NativeScript and JSON, I am currently facing challenges in accessing data from my JSON file. My main goal right now is to simply log some of the data for debugging purposes. Below is the code snippet from my view-model: var config = requ ...

Using media queries in CSS to create responsive designs

<link type="text/css" rel="stylesheet" media="only screen and (max-device-width: 480px)" href="/assets/css/phone.css" /> <link type="text/css" rel="stylesheet" media="only screen and (min-device-width: 768px)" href="/assets/css/tablet.css" /&g ...

Scaling of SVG elements with a fixed canvas size across different end-user resolutions

I am currently using Power BI and the HTML Content visual to create a .svg image. The canvas default size is 1280x720, which cannot be changed. I designed the .svg in Canva at 1920x1080 resolution to accommodate both 720P and 2K users. To make the .svg dyn ...