Utilize express.static to showcase and fetch HTML content before serving JavaScript files

I'm having trouble getting my home.html file to display properly on the browser when I'm using express.static. Here is how my directory and file layout are structured:

dir main
    -server.js
    dir subMain
      dir routing
        -routes.js
      dir public
        -home.html
        -list.html

Here is the code for server.js:

var path = require('path');
var express = require('express');
var app = express();
//Updated path with correct directory names
var htmlRoutes = require('./subMain/routing/routes.js')(app, path, express);

And here is the code for routes.js:

module.exports = function(app, path, express){

    //The path.join should point to 'subMain'
    app.use(express.static(path.join(__dirname + '..')));
    //The path.join should go to 'app'
    app.use(express.static(path.join(__dirname + '..', '..')));
    app.use(express.static(path.join(__dirname + '..', 'public')));

    app.listen(10003, function(){
        console.log('connected on 10003')
    })
}

Currently, I am facing two issues.

1) I attempted to use express.static instead of sendFile because my home.html file contains a link to the jQuery library and routes.js. When I used sendFile, the $ selector was not recognized due to JS loading before HTML. Hence, I switched to using express.static to load all files as shown above.

2) I keep receiving the message 'cannot GET /' in the browser. Even after removing the first two lines of code that utilize app.use(express.static), and having just one line pointing to the HTML in the 'public' directory, I continue to encounter this issue. How can I properly display home.html and ensure it loads fully before my JS file does to use the jQuery selector for a button click event that will trigger an Ajax call to GET /list and show list.html?

Answer №1

It is recommended to define the static directories in the main file of your application (such as server.js) and do so only once.

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

Identify when objects in kineticJS are dropped

Key Concept Designing a match-the-following activity where red dots can be dragged to blue dots on the left. The draggable red dots must accurately match with the blue target dots. Objective Assigning values to each dot, and ensuring that once a red do ...

Using a directive to implement Angular Drag and Drop functionality between two tables with 1000 records

My code is functional, but there seems to be a delay in the appearance of the helper(clone) when dragging starts. I have two tables - one for the include list and another for the exclude list. Users can drag table rows from the include table to the exclud ...

What is the best way to access query string values using JavaScript?

Is it possible to retrieve query string values without using a plugin in jQuery? If the answer is yes, how can this be accomplished? If not, are there any plugins available that can help with this task? ...

Issue: [next-auth]: `useSession` function should be enclosed within a <SessionProvider /> tag in order to work properly

Encountering an error loading my ProfilePage where the page loads fine in the browser but an error appears in the terminal. Error: [next-auth]: `useSession` must be wrapped in a <SessionProvider /> All child components are properly wrapped using Se ...

Utilizing CSS files to incorporate loading icons in a component by dynamically updating based on passed props

Is it possible to store icons in CSS files and dynamically load them based on props passed into a component? In the provided example found at this CodeSandbox Link, SVG icons are loaded from the library named '@progress/kendo-svg-icons'. Instea ...

Remove the initial DIV element from the HTML code

I have created a unique chat interface by combining JScript, php, and jquery. The chat messages are saved in an HTML document that gets displayed in the text area. Each user input message is contained within its individual div tag: <div>Message</ ...

Managing the Response from an Ajax Call

Currently, I am in the process of developing a user registration form for my website and have implemented ajax to manage server-side processes. My main issue lies in effectively handling the response generated by my PHP code. The potential responses from t ...

Using JavaScript, add a complex JSON record to a JSON variable by pushing it

I have been attempting to insert a complex JSON data record into a JSON variable using the following code: var marks=[]; var studentData="student1":[{ "term1":[ {"LifeSkills":[{"obtained":"17","grade":"A","gp":"5"}]}, {"Work":[{"obtained":"13"," ...

Determining if a URL links to an image when the file extension is not informative

I am currently working on building an AJAX call to retrieve data from an API with a messy data structure. The challenge I'm facing is that the array returned by each AJAX call can contain up to 30 elements, some of which have image URLs without a file ...

What is the best way to split a single column into two using blocks?

I am working with a container that currently has all its blocks lined up in a column. I need to divide them into two columns, with 5 blocks in each. Unfortunately, the plugin I am using generates the code for me and does not allow me to insert my own div e ...

One-way communication between two clients using Socket.io

While working on a basic socket.io application using React and Express, I've encountered an issue where two clients are facing difficulties in sending data to each other. For instance: Player 1 connects to the server followed by Player 2. Player 1 ...

Assistance Required for Making a Delicious Cookie

Within my interface, there are two buttons displayed - one is labeled yes while the other is called no. <input type="button" name="yes" onclick="button()"> <input type="button" name="no"> In order to enhance user experience, I am looking to i ...

What strategies can be used to stop elements from reverting to their original state?

Hey there, I'm currently experimenting with animation and trying to create a cool two-step effect: 1. elements falling down and 2. pulsating on click. However, I've run into an issue where after the clicking action, the elements return to their o ...

The Chrome file storage system saves information in files

My challenge is to save data obtained from the Chrome geolocation API into a text file using the Chrome fileSystem API. However, despite successfully creating a file, it remains empty after the process. To simplify, I attempted to add the string '1234 ...

Exploring Node.js and Express routes

Is it possible to have multiple route files in a nodejs+express application and include them into a single file, like the example below? https://i.sstatic.net/Ex0uN.jpg In hotel.routes.js, there are several routes: const express = require("express") ...

What is the best way to adjust the color of the colon within my timer digits using a span element?

I am facing an issue with my timer where the span that was created to display a colon between the numbers does not change color along with the timer digits. I attempted using var colon = document.getElementById(":"); but it still did not work as expected. ...

most effective method for establishing a relationship between a variable and its corresponding identification number

When retrieving results from a database with a simple PHP while loop, one of the data pieces includes a number that links to another table where the corresponding value is stored. While there are various ways to link this information and display the relate ...

Next.js Refresh Screen

Is there a way to refresh my client's web page from the server at a specific time? I need the client's page to be refreshed at 12pm, and although I'm using a scheduler, it doesn't seem to be automatically refreshing the web page on the ...

Vanish and reappear: Javascript block that disappears when clicked and shows up somewhere else

My goal is to make three squares randomly disappear when clicked on the page. However, I am facing an issue where some of them, usually the 2nd or 3rd one, reappear elsewhere on the page after being clicked. I have created a jsfiddle to demonstrate this: ...

Is there a way to extract values from a particular object?

Currently, I am utilizing a JSON server to establish a straightforward login system. The data stored on the server is structured as follows: { "users": [ { "name": "user1", "password": "pass1", "email": "<a href="/cdn-cgi/l/emai ...