To properly render an HTML file before loading a JavaScript file, express.static fails to serve the HTML file

Within my server.js file, the following code is present:

var path = require('path');
var express = require('express');
var app = express();
var htmlRoutes = require('./app/routing/routes.js')(app, path, express);

As for my route.js:

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

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

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

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

The message 'cannot GET /' keeps appearing on my browser. A look into my directory layout reveals the following structure:

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

My goal is to have 'node server.js' load and showcase the home.html page before routes.js. This is crucial as it allows me to utilize jQuery selectors in home.html, targeting a button class and triggering an AJAX call to '/list' to display list.html.

I experimented with the following approach:

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

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

    app.use(function(request, response, next){
        response.sendFile(path.resolve(__dirname + '/../public/home.html'));
    })

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

However, I encountered this error:

Uncaught SyntaxError: Unexpected token <

Further attempts included utilizing multiple lines of express.static:

module.exports = function(app, path, express){
    //loading the directory with the home.html
    app.use(express.static(path.join(__dirname + '..', 'public')));
    //loading directory with server.js by going up two level, from routing directory -> app -> main (has server.js)
    app.use(express.static(path.join(__dirname + '..', '..')))

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


//Edit, added jquery event handler for button click on home.html
$(document).on('click', '.btn', sendSurvery);

function sendSurvery(){

    var myQueryUrl = "http://localhost:10003/survey";

    $.ajax({url: myQueryUrl, method: 'GET'}).done(function(response){

    });
}

Despite these efforts, the issue persists where 'cannot GET /' is displayed. The necessity to showcase home.html first lies in loading the embedded jQuery library, enabling button selection and survey.html transmission upon a click event. An oversight was made regarding the placement of directories 'public' and 'routing,' which are housed within a subfolder named subMain.

Answer №1

Give this a try

Make sure your server file is set up like this

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

require('./subMain/routing')(app, path, express);
    app.listen(9000, function(){
      console.log('connected on 9000')
    })

Also, rename your routes.js file to index.js and keep it in the routing folder with the same name. Update the code as follows. I've changed the port number for you.

      module.exports = function(app, path, express){
    app.use(express.static(__dirname + "/public"));
    app.use(function(request, response, next){
      response.sendFile(process.cwd() + "/subMain/public/home.html");
    })
}

I have shared everything on a GitHub repository for a better overview of the file structure.

GitHub Repository Link

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

What is the best way to incorporate TypeScript into a simple JavaScript project and release it as a JavaScript library with JSDoc for TypeScript users?

Issue: I have encountered difficulties finding an efficient solution for this. Here's a summary of what I attempted: To start, ensure that allowJs and checkJs are both set to true in the tsconfig.json, then include the project files accordingly. Ty ...

Can you explain the concept of an environment variable in the context of Node/Express?

This question may seem basic, but I haven't found a clear explanation for it yet. In my experience with Node/Express, I always set the following variable: var port = PROCESS.env.PORT || 9000 I understand that PROCESS.env.PORT is related to environme ...

Mouseover feature for image is functioning, but having issues with alignment

I am currently working on displaying images upon mouse over actions. While the functionality is working perfectly, I am facing an issue where the displayed images appear below and the last image takes up space at the bottom. To rectify this problem, I woul ...

How can I import a JavaScript file from the assets folder in Nuxt.js?

I have explored multiple methods for importing the JS file, but I am still unable to locate it. Can anyone guide me on how to import a JS file from the assets folder to nuxt.config.js and have it accessible throughout the entire website? nuxt.config.js he ...

Leverage JavaScript to add the rel=0 attribute to a specific URL

Currently, I am integrating videos into my WordPress website using a plugin and I'm looking for a way to ensure that all the YouTube URLs contain rel=0 to eliminate related videos at the end. Can anyone suggest the best approach to achieve this? Any ...

Is there a way to enable code completion for Firebase on VS Code?

After successfully setting up Typescript for code completion following the guidelines provided in this resource, I now want to enable code completion for Firebase in VS Code. However, I am unsure of the steps to achieve this. How can I activate code compl ...

Emulate the CSS hover effect with jQuery 코드 희미한

Is there a method in jquery or any other technology that can detect event X and trigger a different event elsewhere? Currently, I am working with an image that has an image map. When a user hovers over a specific area on the map, I would like another part ...

Executing a function on the window object in JavaScript

I have come across the following code and am seeking guidance on how to get the last line to function correctly. The API I am using currently employs _view appended as its namespacing convention, but I would prefer to switch to something like arc.view.$f ...

Dynamically retrieving markers from the database based on the most recent timestamp of the last loaded batch

I currently have a database where I store marker locations along with their latitude, longitude, type, and timestamp. Right now, my code loads all markers from the database and displays them on the map with different icons based on their type. However, w ...

The "DELETE" method in ajax is malfunctioning

I encountered an "internal server error (500)" in the console. When checking my NodeJS console, I received a "ReferenceError: request is not defined" message. Below is the code snippet that caused the issue: $(document).ready(function(){ $('.dele ...

jQuery Validation is not functioning correctly

I am facing an issue with implementing jQuery.Validation. I have written a script and included all JS files below, but for some unknown reason, the validation always returns that the form is valid. Below is the JavaScript code I am using: $(document).rea ...

Angular code causing an unexpected blank page to be printed again

Trying to display the content of my HTML page is proving to be a challenge. I've been utilizing angularPrint, but an issue persists in the form of a second blank page appearing in the preview alongside the actual content. Eliminating this unwanted sec ...

Interactive quiz program based on object-oriented principles

As I work on developing a quiz app using JavaScript, everything seems to be going well. However, I've encountered an issue with validation where my code is validating the answers twice - once with the correct answer from the previous question and agai ...

Encountering a 404 error when trying to navigate to the next route using the Link component

Having issues with my login route. I've added a Link to the login route inside a button tag in my Navbar component, but when I try to access the route, I'm getting a 404 error page. --app ----pages ------component --------Navbar.js ----- ...

What is the best way to showcase information retrieved using the getDocs function from Firebase Firestore?

Hello! I am currently exploring the world of Firestore and facing a challenge. My goal is to retrieve a data object from Firestore, set it as state, and then display it on my application: Below are the imports that I have utilized for this task (please ig ...

What is the best way to locate elements with the term "download" in them using Selenium's x-path feature?

I'm currently utilizing Selenium for web scraping purposes and I am in need of a way to identify all clickable elements that contain the word "download" (regardless of capitalization) within their link text, button text, element ID, element class, or ...

Show/Hide All Actions in a Vue.js table using Bootstrap styling

In my Vue.js project, I created a bootstrap table to display data loaded from local JSON files. One of the features I added is the ability to Show/Hide details of specific rows, which shows a full message for that row. Now, I'm looking for a way to im ...

UI-Router - templateUrl: "Ensure the content is securely delivered via HTTPS"

I am currently using HTTPS for my website. I have a requirement to send a request for templateUrl, not to a static file, but to the router: /:lang/content/library/book/:bookId Below is the setup for my state: .state('book', { url: '/ ...

An unusual problem stemming from jQuery/AJAX arises when variables within a function fail to update while a click

I've been struggling with a small issue for the past three days that I just can't seem to resolve. It doesn't seem to be a coding error, but rather a misunderstanding of variables and why the onClick event isn't functioning properly. H ...

Creating a stationary div element solely with Javascript, excluding the use of CSS, jQuery, and HTML

I've been searching all day for a solution to this issue without any success. I apologize if I overlooked any relevant posts on the topic. Currently, I am working with Qualtrics and attempting to implement a textbox with scrolling instructions that fo ...