CSS is not appearing on my Node.js server application

The code snippet below is from my node.js server (using express):

app.get('/appointment/:id',function(req,res){
  res.writeHead(200,{'Content-Type':'text/html'});
  res.write('<link href="public/css/style.css" rel="stylesheet" type="text/css">');
  res.write('<form name="accept" action="http://localhost:8080/appointment/'+ req.params.id+'/1" method="post">');
  res.write('<input id="accept" type="submit" value="Accept">');
  res.write('</form><br>');
  res.write('<form name="decline" action="http://localhost:8080/appointment/'+ req.params.id+'/0" method="post">');
  res.write('<input id="decline" type="submit" value="Decline">');
  res.write('</form><br>');
  res.end();
});

In the root directory, there is a folder called appointment with a subfolder named public/css/style.css.
Upon loading the webpage, only the form buttons are displayed without the applied CSS.
Here is the CSS code:

#accept {
  width:50px;
  height:30px;
  background-color:#00FF00;
  color:#FFFFFF;
  font-weight:bold;
  font-size:120%;
}

#decline {
  width:50px;
  height:30px;
  background-color:#FF0000;
  color:#FFFFFF;
  font-weight:bold;
  font-size:120%;
}

What could be causing this issue and how can it be resolved?

UPDATE: The folder structure is as follows:
-server_files
--nodeServer.js
--public
---css
----style.css

Answer №1

It's crucial for me to explain to you the cause of this issue. Just like many other web frameworks, ExpressJs has its own method for serving static files.

The express.static middleware is built on top of serve-static, and its role is to serve the static assets of an Express application.

Here's how it operates:

  • Serve static content for the app from the "public" directory in the application directory

    // GET /style.css etc

    app.use(express.static(__dirname + '/public'));

  • Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static"

    // GET /static/style.css etc.

    app.use('/static', express.static(__dirname + '/public'));

  • Serve static files from multiple directories, but prioritize "./public" over the others

    app.use(express.static(__dirname + '/public'));

    app.use(express.static(__dirname + '/files'));

    app.use(express.static(__dirname + '/uploads'));

Upon reviewing your folder structure, I recommend placing your public directory at the same level as the server_files directory and also moving the nodeServer.js file outside of your server_files as it is the main file you use to launch your application.

In your nodeServer.js, you can do the following:

app.use('/public', express.static(__dirname + '/public'));

By doing this, all your static assets in the public directory can be accessed in HTML templates or any other templating engine you're using. For example:

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

Pay attention to the order of your middlewares in nodeServer.js. I hope this explanation is helpful.

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

Difficulties arise when trying to align text vertically between two floating images

After running the code, I noticed that the text "Text Here" is positioned at the bottom of the div instead of the top. I have attempted to adjust it using properties like vertical-align, padding, and margin-top within the .subText styling, but so far, I ha ...

Incorporating additional information into the database

When I run the code, I see a table and a button. After entering data in the prompts as instructed, the table does not get updated. I'm unsure why this is happening. Can someone please explain? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Trans ...

bitcoinjs-lib for generating raw transactions in Node.js

var bitcoin = require('bitcoinjs-lib'); var rp = require('request-promise'); var data = Buffer.from('Hello World', 'utf8'); var testnet = bitcoin.networks.testnet; var privateKey = 'p2pkh'; var SourceAddre ...

The functionality of HTML labels may be limited when used in conjunction with AJAX

I am using Ajax to load an HTML page and encountering a problem with the label not working properly when associated with a checkbox. Here is the data: <input type="checkbox" name="dis_net" id="dis_net" value="1" /> <label for="dis_net">Test< ...

What is the best way to create separate positions for items within a single div?

https://i.sstatic.net/FQRY4.jpgAfter looping through various names and accessing them from a single div using {{item}}, I encountered an issue. All the names are within one parent element. This is the code snippet: <div :style="image" cl ...

The PHP SDK function works flawlessly in the local host environment and in console, however, it fails to perform on the browser when deployed

My PHP function is behaving differently between the server's command line and the web page, with successful execution on a local WAMP host. Any thoughts on what could be causing this inconsistency? function getCFTemplateSummary($CFUrl){ //init client ...

Adjust the color of a label based on a set threshold in Chart.js

Can anyone help me with my Chart.js issue? Here is a link to the chart: https://i.sstatic.net/RL3w4.gif I am trying to change the color of the horizontal label when it falls between 70.00 - 73.99. Does anyone know if there's a specific option for th ...

In the search for a MongoDB document using Node.js's findOne method, a null response is returned with a

Currently, I am attempting to query a mongodb database. I have defined my Schema as follows: const mongoose = require('mongoose'); const CosmeticSchema = new mongoose.Schema({ code: String, url: String, creator: String, ------------ ...

Button for liking and disliking with Angular, Node.js, and

On my Twitter-esque website, I am developing YouTube-style (like-dislike) buttons. However, when it comes to implementing these like-dislike buttons using Angular, Node.js, and MYSQL with NgFor loop and ngIf conditions, I encountered a problem. My database ...

a dilemma involving syntax and database connectivity issues within a node.js environment

Here is the code I am using for connecting to my database in Node.js: var express = require('express') var mongoose = require('mongoose') var cors = require('cors') var morgan = require('morgan') require('dot ...

What could be the reason for Sequelize's findAll() method returning only a single object?

I am currently facing an issue where I can only retrieve one record out of many similar records when searching for products by brand and model name using Sequelize. This problem occurs even if there are multiple matching records, with the additional ones h ...

Problem arising from selecting checkbox label

Every time I click on the checkbox label, it automatically scrolls to the top of the page. I even removed all scripts and styles from the code, yet the issue persists. My suspicion is that it may be related to the loop, so I am currently investigating fur ...

Arranging 2 divs side by side

As a beginner, I'm struggling to find the answer because I have no idea what search terms to use. Now, I have a form <form action="#" method="POST"> <div id="labels"> <label>CMS System</label><p> ...

Creating a unique design for a CSS menu with distinct section dividers and stylish onHover effects

Hey there! I'm currently working on a new menu design using UL and LIs elements. I would really appreciate some advice on how to add lines after each LI and properly indent them with the specific bullet image I have chosen. If you're interested ...

Is it possible to have individual submit buttons on forms that instruct the form where to post its "action" to different files?

I have decided to enhance my form by incorporating an extra Submit button for a specific purpose. User will make a selection User will click on the "Add another item" Submit button within the form. The form will then POST to itself and reload the page, a ...

When an image is loaded, use Jquery to automatically open a new tab, instead of

I need to implement a function where, on loading an image on a page, a new tab opens and starts downloading a file from a specific URL while keeping the original page open. This task is part of a WordPress site with a jQuery section in the backend. I' ...

Utilizing AngularJS to bind data with labels and passing it in a form

I'm having trouble binding input data with label tags and using the same ng-model in a post method. Only one thing works at a time, and when I try to pass the label in the post method, it doesn't work. This issue is causing me difficulty in delet ...

Notification from the background has been received and parameters have been restored

Sending a post request from "angular->port 4200" to "expressjs server->port 8000". Referencing this example: https://github.com/kuncevic/angular-httpclient-examples/blob/master/client/src/app/app.component.ts Encountering two errors: 1) Undefined ...

Navigate seamlessly with the dynamic navigation system on Express.js

Are there any dynamic navigation plugins available for Express JS 4.0 that are compatible with Passport? I've been searching, but haven't found one yet. The basic idea is as follows: When a user is logged in, they can see the routes they have ...

Align the content to the center of the middle column using HTML

Is it possible to replicate Amazon's email structure using only HTML in the feedbackwhiz template editor? I want my content to be left-justified in the center column with white space on either side, similar to the Amazon email example provided. Amazo ...