The Express.js server seems to be having trouble rendering a static JavaScript file

Currently, I am in the process of constructing a website and have implemented an express.js server to collect data submitted through a form. Prior to configuring the server, I had already developed the site using static js and css files. Once the connection to the server was established, the server successfully rendered the html and css stylesheet. However, it seems to be encountering issues displaying the vanilla js that was previously coded. My intention is to utilize the server solely for the form submission while still allowing the vanilla javascript to render as it did prior to the server integration.

The file structure is organized as follows:

root
index.html
app.js
  public
     css
       styles.css
     javascript
       index.js

In app.js:

const express = require("express");
const https = require("https");
const path = require('path')
const app = express();
    
    
app.use(express.static(path.join(__dirname, '/public')));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
    
    
app.get("/", function (req, res) {
    res.sendFile(__dirname + "/index.html");
});

In index.html:

<link rel="stylesheet" href="css/styles.css" />
<script src="javascript/index.js"></script>

I appear to be facing difficulties with integrating the vanilla js file after connecting it to the server. Is there something specific I should include within my index.js file to establish a successful connection with the server? Any guidance on resolving this issue would be greatly appreciated.

Answer №1

1. Incorporate this middleware into your app.js

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

2. Organizational Layout

|__public/   
    |__ css/
        |__ css files...
    |__ js/
        |__ js files...

3. Utilize This Method for Importing

When setting the path to the public directory, remember to specify the path to the public folder when importing

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

<script src="/js/main.js" crossorigin="anonymous"> </script>

You are now fully configured to access CSS and JS files

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

Can you tell me how to designate a specific SSH key for npm install?

I am looking to add a private repository to my package.json file. "private-module": "git+ssh://<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f58564b7f5d4c294345">[email protected]</a>:private/private-module.git ...

Unable to insert the object into the array following the execution of the MongoDB query

I'm facing an issue while trying to add items into an array based on ids received by the Express server from a client. The program is set up to receive the product id, fetch details of the product using a MongoDB query findOne, and then customize the ...

Update specific fields in a MySQL database using Express.js only if they are passed as parameters

After spending several days trying to set up a REST API, I found a helpful tutorial that explained the basics of sending requests and receiving responses. The only issue is that the tutorial uses MongoDB and Mongoose, while I'm working with MySQL. Due ...

The way to find the prefix for the npm global path

Is there a specific option to pass to npm that will display the path it uses for global modules (-g)? Alternatively, is there another method to determine the global path prefix used by npm? I am aware of the location where global modules are stored on my ...

Creating a worldwide entity through the use of an Immediately Invoked Function Expression

There are 2 methods I discovered for defining a global object using IIFE: (function () { var func = function () { }; window.func = func; }()); compared to: (function (myFunc) { window.func = myFunc(); }(function () { var func = functi ...

Using Regular Expression in JavaScript to replace variables within a string

Looking for assistance to replace keywords in a string with pre-defined variables. Currently, the code only displays variable names instead of their content. Can anyone provide help? Desired Output: 1111Test1 2222Test2 3333Test3 Current Output ...

Adjusting the width of a nested iframe within two div containers

I am trying to dynamically change the width of a structure using JavaScript. Here is the current setup: <div id="HTMLGroupBox742928" class="HTMLGroupBox" style="width:1366px"> <div style="width:800px;"> <iframe id="notReliable_C ...

Avoid receiving input for a button that is being covered by another button

I am currently developing an Idle Game and I am looking to include 'buy buttons' for purchasing buildings, along with a sell button embedded within the buy button. Just as a heads up, these buttons are represented by DIVs acting as buttons. Here ...

What could be causing my HTML elements to shift position based on varying screen sizes or zoom levels?

Does anyone else experience their HTML and CSS elements shifting around based on the screen size or zoom level? I have screenshots illustrating this issue. Here is how it currently appears And here is how it's supposed to look ...

Encountering persistent issues while attempting to integrate socket.io into my Node.js application with Express

Recently, I've been exploring ways to create a textbox that allows multiple users to type simultaneously. Below is the HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> ...

Improving code quality and consistency in Javascript: Tips for writing better code

Hey, I've been experimenting with some code using ajax and have ended up with a lot of repetitive lines. Is there a way to streamline the code without losing functionality? I keep using the .done method multiple times when I could probably just use it ...

Is it necessary to implement both JWT and Passport in a Node application?

I've been delving into the intricacies of user login authentication process for my MERN app that I'm currently developing. Most tutorials I come across advocate for using both passport in conjunction with jwt, and I find myself struggling to gras ...

Is it possible to upload a file in Node directly to a stream without the need to first save it to a temporary

Is there a way to directly stream Node.js file uploads to a remote server or fileshare without saving them as temp files on my server first? I am currently using formidable, but it seems to always save the file locally before uploading. It would be more ef ...

Top spot for locating resolve functions in AngularJS

I'm currently in the process of setting up resolves for my admin panel routes and I'm pondering the best way to store them without cluttering my router with methods. Here's what I have so far: when('/admin', { templateUrl: &ap ...

Encounter a snag while using Chrome to access an external API through jQuery

I am currently utilizing jQuery to make a request to an external API via AJAX. $.ajax({ url: https://exampleAPI, method: "GET", contentType: "text/plain", dataType: "jso ...

What could be the issue with my JSON data stream?

Trying to set up the Fullcalendar JQuery plugin with a JSON feed has been a bit of a challenge. The example provided with the plugin works perfectly, so it seems like there might be an issue with my own feed. Here is the output from the working example JS ...

Attempting to retrieve JSON data and present it in a grid layout

I have a JSON file with the following data: { "rooms":[ { "id": "1", "name": "living", "Description": "The living room", "backgroundpath":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSrsU8tuZWySrSuRYdz7 ...

Creating captchas seems like a mistake in reasoning to me

I am encountering an issue with my code. I created a basic newbie-level captcha using Javascript. Below is the code snippet: <!DOCTYPE html> <html> <head> <style> </style> </head> <body> <h1>T ...

Using Sequelize to increment a value and update the updated_at field in a single method

Is it possible to increment a value and update the updated_at column in Sequelize with a single call? Given that using the increment method updates the table, it seems like the updated_at column should be updated simultaneously without requiring a separate ...

The route param is throwing a "Cannot read property 'name' of undefined" error, indicating that the property

Currently, I am enrolled in an ExpressJS course on TUTS+ From the video tutorial, I have implemented the following code snippet (excerpt from video): var express = require('express'), app = express(); app.get('/name/:name', funct ...