When attempting to access index.html, the Express Server responds with a "Page Not Found"

I have encountered a problem while trying to run my Index.html file through an Express server. Despite referring to previously asked questions, I couldn't resolve the issue. The error message 'Cannot GET /' keeps popping up.

Below is the snippet of my server.js file where I attempt to call the index.html:

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

app.get('index.html', function (req, res) {
  app.use("/", express.static(__dirname));
});

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});

Any help or insights would be greatly appreciated. Thank you in advance!

Answer №1

When you access a directory on your hosted site, like the root directory of localhost on port 8080 by using http://localhost:8080/ in the URL, the browser does not send a request for 'index.html' to the server but rather uses whatever the server sends back.

The express static middleware comes into play here - it responds to a browser request with no filename by checking if the folder exists and (by default) returns any index.html file contained within that folder. So in this scenario, your routing code line, app.get('index.html'), doesn't get executed, leading to an error message being displayed by the browser.

If you'd like to experiment with a simple static express server, you can use the following code snippet:

var express = require('express');
var app = express();
app.use(express.static('../public')); // adjust the path to point to your public directory

var server = app.listen(8080, function () {
   var host = server.address().address;
   var port = server.address().port;
   console.log('Example app is listening at http://%s:%s', host, port);
 });

Answer №2

For a straightforward approach to setting up a basic static server without using Express, you can create a simple folder-based server like so:

var fs = require("fs");
var host = "localhost";
var port = 8000;
var express = require("express");

var app = express();
app.use('/', express.static(__dirname));
app.listen(port, host);

I typically save this code in a file named server.js, located in the same directory as my index.html file (and even associate the .js extension with node.exe). This setup allows the folder itself to serve as the root of the server.

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

Providing a public API that exclusively grants access to requests originating from my own website

After hours of scouring Google and SO, I have yet to find someone facing the same challenge I am encountering now. Here's the situation: We have invested a significant amount of money and effort into maintaining a database. The data from this databas ...

Unveiling the secret to accessing the table itself from dtOptions in AngularJS-Datatables

I'm trying to create a download button for a CSV file, but I need to exclude specific columns from the table. I have discovered an option called "exportOptions" that is used in jQuery DataTables to define which columns should be exported. It seems th ...

Function wrapper intended for axios

How can I create a wrapper function for axios? I am looking to create a function that can return axios, allowing for easy substitution with another fetch API in the future. This is what I have attempted so far: import axios from 'axios' expor ...

AngularJS Treeview - Rearranging tree nodes

My journey with Angular is just beginning, and I managed to create a treeview following this example: jsfiddle.net/eu81273/8LWUc/18/ The data structure I've adopted looks like this: treeview1 = [ { roleName: "User ...

Tips for changing input field type from "password" to "text" in Angular?

Is there a way to dynamically convert an input field with type="password" to type="text" in Angular? In my demo, I have two input fields labeled Mobile no and Re-enter mobile number. I want these fields to change to type="text" if the user inputs the same ...

Retrieve the value of a selected element

I currently have an HTML select drop down that is populated by a JQuery get request. You can see this in action at this link. My goal is to access the specific piece of code for the selected value every time it changes. <small class="text-muted"> ...

Having trouble retrieving cookie in route.ts with NextJS

Recently, I encountered an issue while using the NextJS App Router. When attempting to retrieve the token from cookies in my api route, it seems to return nothing. /app/api/profile/route.ts import { NextResponse } from "next/server"; import { co ...

"Steady layout of grid for the navigation bar and

Currently, I am in the process of developing a control panel with the use of HTML and CSS. To structure the page, I opted for a grid layout. However, I encountered an issue where the navbar and sidebar do not stay fixed on the screen despite trying various ...

update the dropdown values in the database by submitting the form

Members sign up for the website. The administrator will log in and access a list of users. I am attempting to provide an option for the admin to select a checkbox and update the user's status through a dropdown menu submission. When I tested the code ...

Transform HTML content into a PDF document with page breaks

Currently, I am developing a function that involves an HTML template. The purpose of this function is to generate a dynamic template and convert it into a PDF. So far, I have been able to achieve this using the following code: var output = ''; ...

What methods are available for parsing JSON data into an array using JavaScript?

I possess an item. [Object { id=8, question="وصلت المنافذ الجمركية في...طنة حتّى عام 1970م إلى ", choice1="20 منفذًا", more...}, Object { id=22, question="تأسست مطبعة مزون التي تع... الأ ...

Issue with timestamp in the Instagram API call to retrieve media using AJAX (GET /media/search)

My API call is returning a 400 bad request error message: {"meta":{"error_type":"APIInvalidParametersError","code":400,"error_message":"invalid parameters-check the max\/min-timestamps, if you supplied them"}} Even though my request appears to be co ...

The Ion slider's onFinish event is triggered when the page loads, independent of any user interaction with the slider

I am facing an issue with ionslider. I have observed that the plugin triggers the onFinish action without any user interaction when the page is loaded. However, on the demo site ionden.com/a/plugins/ion.rangeSlider/demo_interactions.html, the plugin only r ...

Incorporating Keyboard Features into Buttons

How can I toggle the page selectors in #pageList using a keyboard shortcut instead of clicking on the .togglePL button? I've tried looking up solutions online and asking questions here, but haven't found a working solution yet. Below is the code ...

Incorporating a new element into a JavaScript array

I recently used a vue.js library that has a specific requirement for arrays in this exact format autocompleteItems: [ { text: "Python" }, { text: "HTML" }, { text: "CSS" }, { text: "React ...

Issue encountered with invoking carousel.to() method in Bootstrap 5

// Create a new carousel instance let car = new bootstrap.Carousel(document.querySelector('#carouselMenu'), { interval: 0, wrap: false }); // <SNIP> // Go to page at index 1 car.to("1"); Error: https://i.sstat ...

What steps should be taken to create a two-column table from a given list of items?

I am trying to display a list of words in two columns, one word after another from left to right. Here is the desired table structure: <table id="wordTable"> <tr> <td>ac </td> <td>bd </td> </tr> ...

Eliminate the use of quotation marks in the AJAX response

The response returned as "4", instead of just 4 I attempted changing it to .done(function(data)) but the outcome remained the same $.ajax({ url: "../api/ajax/addToCart.php", type: "post", data: data }) .done(function(response) { // alert( ...

Deleting a string from a parameter

I have a string that reads: France (Republic of France) I am trying to extract only "France" and remove the rest of the string in parentheses. France (Republic of France) Any tips on how to achieve this? Thank you. ...

Include two additional elements for action in a list

In my React project, I've created a list with the following elements: Avatar Text Edit icon Delete icon I managed to set up the structure successfully up until the delete icon. Now, how can I properly add it without overlapping the edit icon? Both ...