When using Express.static, the website functions properly but an error message "GET http://localhost:5000/index.js net::ERR_ABORTED 404 (Not Found)" is displayed

Having an issue with express.static.

My project is a basic portfolio website that includes a form for sending emails. I referred to this tutorial on Nodemailer: Tutorial Nodemailer Github

The problem arises within my index.html file (this example applies to all .html files in the project) where I have:

<script src="/Public/index.js"></script>

for including my .js file.

Project folder structure can be seen here: Folder tree

When the script is included this way, no errors occur. However, upon sending an email, the webpage fails to load and does not redirect to /send.

If I include the script like so:

<script src="../index.js"></script>

It works correctly - the website redirects after sending the mail. But then I encounter this error message:

GET http://localhost:5000/index.js net::ERR_ABORTED 404 (Not Found)

I've looked into similar posts where incorrect usage of express.static was identified as the issue. It seems likely that I made some mistakes with it, but I'm struggling to pinpoint them.

In my server.js, I've added the following code for express.static:

app.use("/Public", express.static(process.cwd() + "/Public"));

And for routing, I use:

app.route("/").get(function (req, res) {
  res.sendFile(process.cwd() +"/Public/html/index.html");
});

Any assistance in understanding this issue would be greatly appreciated.

This is the index.js code snippet:

const form = document.getElementById("contact-form");
const formEvent = form.addEventListener("submit", (event) => {
  event.preventDefault();
  let mail = new FormData(form);
  sendMail(mail);
});

const sendMail = (mail) => {
 fetch("/send", {
 method: "POST",
 body: mail,
}).then((response) => {
  return response.json;
});
};

Answer №1

When utilizing the express.static middleware, all you have to do is specify the folder from which static files should be served. No specific route is needed for this method, and you can also use path to resolve the file path:

app.use(express.static(path.resolve('Public')));

The problem you're encountering may be due to the script URL. When including your index.js with a relative URL like ../index.js, it works because it is relative to the currently loaded file index.html but one level up in the folder structure.

<script src="../index.js"></script>

If there are issues with /Public/index.js, keep in mind that the 'Public' folder serves as the root for your static files. To use an absolute URL for the script, avoid including the 'Public' folder in the URL:

<script src="/index.js"></script>

Following these steps should resolve the issue and ensure proper loading of your script.

Answer №2

Transitioning the solution proposed by OP from the initial query to a response:

I successfully tackled this issue by implementing the following:

<script type="javascript" src="./index.js"></script>

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

Prevent draggable functionality of jQuery UI on elements with a specific class

I have created a dynamic cart feature where users can drag and drop items into the cart. However, once an item is placed in the cart, it should no longer be draggable (though still visible but faded). I attempted to achieve this by using the following code ...

What is the process for implementing document.ondrop with Firefox?

I'm experiencing an issue where the document.ondrop function seems to be working in Chrome, but not in Firefox. Here's a link to an example demonstrating the problem: In the example, if you try to drop a file onto the page, it should trigger an ...

Guide to implementing the Office 365 Javascript API in your application

Looking to integrate an Office 365 Excel sheet with the necessary toolbars into my web-based application, similar to this setup (including the Excel Online toolbar above). Link Here Unsure of the process - is there a way to implement tables and toolbars ...

Customizing the styling of a TextField component in ReactJS using material-ui

I am currently working with Reactjs and material-ui. I am looking to apply some custom styles to a TextField using css. Specifically, I would like to change the color of the TextField underline and label when the input is clicked. Although I know it can b ...

Switch up your Vue filters with ease

I'm struggling to create filters in Vue that work with arrays of colors and objects called products. I also have a property called count to keep track of clicks: data() { return { count: 0, colors: [ 'red', ...

Use Node.js with Selenium and WebdriverIO to simulate the ENTER keypress action on

I have put in a lot of effort trying to find the solution before resorting to asking this question, but unfortunately I have not been successful. All I need to know is how to send special characters (such as the enter key and backspace) with Node.js using ...

Unable to retrieve translations using language header in axios are not successful

My goal is to create a single-page website with multiple components. I am facing an issue where only one language appears instead of fetching translations from the API for each component. When using Promise.all() in the index page, the translations do not ...

Customizing image clusters on Google Maps is a great way to

I have been trying to customize Google map clustering with a custom image, but no matter what image I provide, it doesn't seem to change. The initMap function looks like this: https://developers.google.com/maps/documentation/javascript/marker-clus ...

I am attempting to monitor the addliquidity event on Uniswap's router02

I am currently attempting to monitor addliquidity events in order to extract data on newly added pairs const Web3 = require('web3'); const NODE_URL = "https://mainnet.infura.io/v3/d3c5832256754c85be86b4c97de2d3d3" const web3 = new We ...

What is the best way to convert a JSON object back into an object with its own set of methods?

Currently, I have a JavaScript object with multiple methods attached via prototype. When I serialize the object to JSON, only the property values are saved, which is expected. It wouldn't make sense to save the methods as well. Upon deserialization ...

I'm wondering if there is a method for me to get only the count of input fields that have the class "Calctime" and are not empty when this function is executed

Currently, I am developing an airport application that aims to track the time it takes to travel between different airports. In this context, moving from one airport to another is referred to as a Sector, and the duration of time taken for this journey is ...

Creating an ImmutableJS Record with custom types: A step-by-step guide

Is there a way to make ImmutableJS Records throw runtime exceptions if fields are missing instead of needing default values? ...

Encountering an issue with Angular virtual scrolling: ViewDestroyedError arises when trying to utilize a destroyed view during detectChanges operation

My implementation involves using virtual scrolling from the cdk within a trigger-opening sidenav on a mat-radio element. Here is the code snippet: ts - ... @Component({ selector: 'app-generic-options-list', templateUrl: './generic-opt ...

Deliverer - Sending JSON formatted data through the post

Is there a way to successfully send application/json data using Postman and receive the same data as req.body in a Node.js server? I attempted to send the data as raw body json in Postman, which did successfully send it as application/json, however it ar ...

The isolate scope variable is becoming undefined within the link function

When working with a directive that takes a data object and a function in its isolate scope, I encountered an issue. Inside the link function, I declared a method to be triggered on a button click event. The problem is that while the value passed to the me ...

Using Functions outside of React Components

I am having trouble figuring out how to update a shopping cart when I click on a product. The function is written in one component, but I need to call it from another. Here is where the function is defined and the cart state is maintained: export const ...

The Vue router is unable to access the store state

My Vue application is utilizing vue-router and vuex. I acquire an authentication token from my API, store it in localStorage, and then push it to the store. However, when the page refreshes, the app is unable to retrieve the token from localStorage and the ...

Generating a USA map with DataMaps in d3jsonData

I'm trying to create a basic US map using the DataMaps package and d3 library. Here's what I have attempted so far: <!DOCTYPE html> <html> <head> <title> TEST </title> <script src="https://d3js.org/d3.v5.js"> ...

How to format a date in ngModel using Angular 9 and above

Is there a way to format the date displayed in my input using ngModel to follow a specific format like 'MM/dd/YYYY'? Can this be achieved by using ngModel? For example, could we do something like model[(ngModel)]="data.targetDate | date:'MM ...

unable to comprehend the remaining section

My divs are not checking/unchecking properly. The else part of my code is unable to read it and displays 'undefined'. Please assist me... (The first click works correctly but the second click shows 'undefined') import React, { useState ...