Sending a styled HTML file as a response to a connected client through Express

I have been struggling to solve this issue for quite some time now. The answers I have come across have been confusing, lacking explanation, or simply not working for me.

Let me provide you with an overview of my project structure.

.. indicates a folder
- indicates a file
while four | indicate a subdirectory or file within a parent folder

..public
|||| ..html&css
|||| |||| ..main
|||| |||| |||| - main.html
|||| |||| |||| - main.css
|||| ..javascript
|||| |||| -server.js

Hopefully, the above description of my project structure is clear. Formatting on Stack Overflow can be tricky to work with.

Now, let me share the code from my server.js file:

let express = require('express');
let app = express();

app.use(express.static('../html&css'));

let server = app.listen(8080, function () {
    app.get(function (req, res) {
        res.sendFile();
    });
});

let port = server.address().port;
console.log(`Express app listening at ${port}`);

I have encountered various methods to send files when a user connects to the server. However, I have only been able to successfully send HTML and not CSS. While researching solutions, I have found explanations to be confusing and lacking in detail regarding how to achieve my specific goal.

Terms like routes, static, app.get, res.sendFile, and other technical jargon are being used without clear explanation. It would be helpful if the responses included the complete project structure so that understanding the functioning of different routes becomes easier.

I stumbled upon this link, which seemed to offer a potential solution. However, due to the absence of a project structure, implementing it in my own project has proven challenging.

If someone could kindly clarify how this solution works with an implemented project structure, I would greatly appreciate it. Alternatively, if there is another approach involving the use of the fs module in conjunction with Express or any other method, please do share.

I hope my question is clear and understandable. Thank you for your assistance.

Answer №1

Allow me to clarify how this functions. The code you've written is accurate, as I've tested it myself.

let express = require('express');
let app = express();

app.use(express.static('../html&css'));

let server = app.listen(8080, function () {
    app.get(function (req, res) {
        res.sendFile();
    });
});

let port = server.address().port;
console.log(`Express app listening at ${port}`);

So, what does express.static do exactly? It exposes a specific folder and creates automatic routes.
For example, if you wish to access main.css, it will be available at localhost:8080/main/main.css. In your main.html, you simply need to add a link to that CSS file.

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

However, you cannot perform an HTTP GET request on something like localhost:8080/main; it won't work.

Therefore, you must run the server by entering node javascript/server.js and it should work smoothly. Since the server.js contains backend code, avoid placing it in the public folder. Instead, consider creating a separate folder called src for it.

Answer №2

Let's explore a few key points.

Firstly, consider the directory structure:

Based on your current configuration, your server.js file is located within the public folder, but nested one level down.

If we think in terms of an MVC framework, take a look at this example tutorial: sample tutorial. Ideally, you should place your server at the root of your application (not inside the JavaScript folder within the public directory where client-side JavaScript would typically be served).

Secondly, regarding middleware:

When utilizing the express.static middleware, it's recommended to use the path module to generate an absolute path rather than a relative one to the public folder, especially crucial for deployment purposes.

app.use(express.static(path.join(__dirname, 'public')));

Following this adjustment, you'll have access to all files in your public folder via:

http://localhost:8080/main/*
http://localhost:8080/javascript/*

Note that * signifies any existing files in the directories.

Thirdly, concerning the app.listen function:

The callback function for app.listen expects a returned server object. Refer to the documentation. Rather than defining a listener on a route here, it's preferable to do so outside of the app.listen invocation.

For example, you might establish a basic get route to serve your main.html page at /, or choose another setup. The express.static middleware is already serving this page as /main/main.html.

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname, 'public', 'main.html'));
});

let server = app.listen(8080);

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

Creating shapes with CSS and Vue

I've been attempting to replicate this design on my website using CSS and Vue, but I'm struggling to achieve the desired result. As a newcomer to this, I could really use some guidance. Here is my goal: https://i.sstatic.net/WI9Wr.png This is ...

Is there a way to view an HTML file without downloading it first?

Hello there, I have a situation where I am storing a string as the content of an HTML file within my application. Is there a way for me to preview this modified content in a web browser without having to save it locally? Update Additionally, is there a ...

Looking to dynamically adjust row color based on status using ANGULAR 4

In my table, I have 6 columns: name, email, phone, company, status_1, and status_2. Both status_1 and status_2 can have two options: "1" or "0." My Requirement: I want to change the color of the row based on the following logic: if(status_1 is "1" ...

Is it possible to simultaneously employ two asynchronous functions while handling two separate .json files?

Is it possible to work with 2 .json files simultaneously? My attempt did not succeed, so I am looking for an alternative method. If you have a suggestion or know the correct syntax to make this work, please share. And most importantly, does the second .j ...

Securing data retrieval with React App and node.js backend API

Recently, I set up a React-App and a separate Node.js/Express Application on a server. I want the React App to be able to fetch data from the Node Application, but I need to prevent outside access to those API calls, whether it's through requests, dir ...

Is there a way to make item 1 dynamically update when I hover over item 2?

How can I create a function that enlarges item 2 when hovered over, while causing item 1 to shrink and rotate its text? Is there a way to achieve this effect using CSS or JavaScript? Currently, I have managed to make the hover effect work on item 1, wher ...

Launching a Phonegap app using Node.js and Express framework

My goal is to transform my current webapp into a mobile app. The existing setup consists of a nodejs-express REST API server with an HTML/JS client. I aim to utilize the API from the REST server and replace the client with a phonegap/cordova based mobile ...

Easily showcase a limitless number of items within a 10-column grid using Bootstrap!

This is the code snippet: <div *ngFor="let minute of state.minutes.specificMinutes.selectedMinutes | keyvalue" class="col-sm-1 checkbox-container"> <div class="custom-control custom-checkbox"> <input type="checkbox" (click)="state.m ...

Having trouble deleting files in PHP?

I am presenting an HTML form below: <form action='delete.php' method='POST'> <table> <div class = '.table'> <?php $dir = '../uploads/store/'; $new ...

Are JSON-Web Tokens (JWTs) used for both verifying identity and granting access privileges?

Currently, I am exploring the process of developing a blog website that permits users to log in and perform tasks such as editing or deleting their own blogs based on their user role. If a different user logs in and does not own a particular blog, they s ...

Exploring the Use of Regular Expressions in JavaScript to Extract Content Enclosed by

I am struggling to extract the content between XML tags without including the tags themselves. Just to clarify, I will be utilizing RegEx in JavaScript and not for parsing XML. Therefore, lookbehind won't be applicable. Where could I possibly be goi ...

Verifying certain requests in Node.js for enhanced security

I recently developed an API by using the guidance from this source. The authentication process is done as shown below: router.post('/authenticate', function(req, res) { var query = "SELECT * FROM ?? WHERE ??=? and ??=? LIMIT 1"; ...

I'm encountering difficulty displaying my caption in the lightbox feature

I have a lightbox set up to scroll through images, but after adding forward and back buttons, I lost the caption that used to be displayed. Can anyone help me solve this issue? Your assistance is greatly appreciated. var $overlay = $('<div id="ove ...

Issue with displaying background image in mobile device despite successful display in browser and Chrome tools on Angular 18

Revamping my personal website (www.coltstreet.com) led me to explore media queries for displaying different background images. Testing on desktop and via Chrome tools showed positive results, but the real challenge arose when viewing the site on my actual ...

Is it acceptable to duplicate and replace content directly from the Google Inspector tool?

As I work on creating a new woocommerce checkout page, I encountered some issues. My approach to extracting code from woocommerce involved inspecting the Code and copying it directly into my checkout file at /woocommerce/checkout/checkout.php. Is this met ...

Limiting zero is ineffective when it comes to pop-up issues

Hey there, I'm looking to prevent users from inputting zero and dot in a specific field, which is currently working fine. However, when the field is within a pop-up, the code below doesn't seem to work. <script> $('#name').keyp ...

Modifying HTTP status while streaming content with renderToNodeStream

I am currently working on implementing streaming rendering in my project. Here is a snippet of what I am currently doing: // Example code snippet res.write(htmlHeader) const renderingStream = renderToNodeStream(<App />); renderingStream.pipe(res) ren ...

`Manipulate the class attribute in HTML by utilizing jQuery or JavaScript`

Is it possible to modify this particular line of code? <li id="activehome" ><a href="#" >Home</a></li> to this: <li id="activehome" class="active"><a href="#" >Home</a></li> I need assistance on h ...

What methods can be used to identify the specific Router component being rendered in React?

I am currently working with a Navbar component that I want to render with different CSS styles using styled-components based on the route of the component being rendered. How can I determine whether that component is being rendered or not? const NavbarCont ...

Setting up a connection to MongoDB on a local network using express and mongoose

As I set up a server with express and mongoose, my goal is to make it accessible on other devices within my local network. To achieve this, I configured the bind_ip variable to 0.0.0.0 in the Mongodb configuration file. const connection = mongoose .co ...