My Express server is having trouble loading the Static JS

I'm feeling frustrated about this particular issue. The problem seems to be well-solved, and my code looks fine, but I can't figure out what's wrong . . .

I have a JavaScript file connecting to my survey page, which I've added at the bottom of the <body> tag like this:

<script type="text/javascript" src="/static/questions.js"></script>

In my server.js file, I've tried:

app.use(express.static('public'));
app.use(express.static('data'));
app.use('/static', express.static('public'));
app.use('/static', express.static('data'));

I thought I covered all bases there . . . 'public' contains the HTML pages, while 'data' holds my JSON and JavaScript files.

Directory structure:

root
-app
--data
--public
server.js

However, I keep encountering a failure to load JS error.

https://i.stack.imgur.com/fnDQ5.png https://i.stack.imgur.com/Ly9Et.png

What's going on here?

Answer №1

The reason for the issue is that you forgot to send the js file to the user when a request is received by the server

For example, you need a js file called public.js

File path: ui/publish.js

Request URL: http//:localhost:4000/ui/publish.js

app.get('/ui/publish.js', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui', 'publish.js'));
});

Give this a try.

Answer №2

Give this a shot.

Format
main-node
-app
--info
  -- file1.js
  -- file2.js
--assets
   -- page.html
server.js


app.enable(express.static('assets'));
app.enable(express.static('info'));

Now, to access file1.js, use the URL http://localhost:8080/file1.js and for the html file, use http://localhost:8080/page.html

Answer №3

<script type="text/javascript" src="/newquestions.js"></script>

It is recommended that you update your script tag as shown above and include the following line in server.js:

app.use(express.static(path.join(__dirname, '/app/static')));

Ensure that your js files are placed in the /app/static directory.

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

Is there a way to verify if a Backbone.View is actively displayed in the DOM?

Is there a way to determine if a Backbone.View is currently rendered in the DOM, so that I do not need to rerender it? Any suggestions on how this can be achieved? Thanks and regards ...

Enhance the functionality of jQuery sortable by including additional details

I have a li list that I have implemented sortable functionality using jQuery. In order to ensure that the updated data is sent to the correct destination, I need to include some hidden values in the serialized data. How can I achieve this? HTML <ul i ...

Hapi/Node.js Reference Error for Request: Troubleshooting the Issue

I am facing an issue with my two API handlers: module.exports.loginWeb = function (request, reply, next) { if (request.auth.isAuthenticated) { return reply.redirect('/'); } if(request.method === 'get'){ rep ...

Passing data retrieved from a mongoose query to a webpage without the need for a page refresh

I need assistance with updating my website functionality. Currently, I have a link on my site that triggers a function performing a mongoose query when clicked. However, instead of reloading the entire page with the new query results, I want to display the ...

Launch all external links in Browser (NWjs)

While attempting to create my own independent version of Google Chat using NWjs, I encountered some obstacles. When a link is opened in the NWjs window, it opens in another NWjs window instead of the default system browser, which is what I want. I attemp ...

Hierarchy-based state forwarding within React components

As I embark on the journey of learning Typescript+React in a professional environment, transitioning from working with technologies like CoffeeScript, Backbone, and Marionettejs, a question arises regarding the best approach to managing hierarchical views ...

refetchQueries may be effective for specific queries

Using a Friend component within my AllFriends screen triggers the following mutation: const [deleteUserRelation] = useDeleteUserRelationMutation({ onCompleted: () => { Alert.alert('Unfriended'); }, refetchQueries: [{ query: ...

Tips for keeping a login session active on multiple tabs

As I am in the process of developing a website, one issue I am facing is determining the most effective method to maintain user login sessions. Currently, I am utilizing Html5 web storage known as "session storage" to keep track of whether a user is logged ...

The persistent issue persists with the Sails.js Node server where the req.session remains devoid of any data, despite utilizing

Currently, I have an Ember app running on http://localhost:4200 and a Sails app running on http://localhost:1337. In order to set up a pre-signup survey policy in my Sails application, I have the following code in /api/controllers/ProcessSurveyController. ...

Calculate the total cost for each row in a table by multiplying the quantity and price using jQuery, then display the result

I'm encountering an issue with my table row calculations involving price and quantity. The calculation results show up correctly in the console, but when I try to display them back on the table, the total sum of the first row gets duplicated into all ...

Showing error messages in Angular when a form is submitted and found to be invalid

My form currently displays an error message under each field if left empty or invalid. However, I want to customize the behavior of the submit button when the form is invalid. <form #projectForm="ngForm" (ngSubmit)="onSubmit()"> ...

Transitioning create-react-app from JavaScript to Typescript

A few months ago, I began a React project using create-react-app and now I am interested in transitioning the project from JavaScript to TypeScript. I discovered that there is an option to create a React app with TypeScript by using the flag: --scripts-v ...

Sorting Columns in JQuery Datatables

Encountering an issue with JQuery DataTables (datatables.net) where it takes 2 clicks to sort the columns when there are only 2 rows in the table. The first column sorts on the first click, but subsequent columns require multiple clicks. Despite testing th ...

Is there a reliable method for parsing a CSV file that contains JSON strings as values?

When parsing CSV files, I encountered values that include strings representing JSON objects, along with boolean, normal strings, and other data. The CSV file has a header, and as I loop through the non-header rows, I utilize Javascript's split method ...

Escape from an iframe with the help of a buster

My website is being targeted by a code that prevents it from breaking out of an iframe. Despite trying different frame breaker scripts, I have not been successful in resolving this issue. Any assistance would be greatly appreciated. Thanks! Buster: func ...

Ways to avoid scrolling on a fixed element

Here is the HTML setup I have... body .top .content The issue I am facing is that when scrolling reaches the end of the ul in the .top element, the background starts to scroll. This can be quite disorienting and makes the site slow on tablets. Even ...

Is there a way to mimic disabled input fields?

Is there a way to simulate input being disabled without actually changing the value in the input field, but still have that value sent with POST using a form? <input class="dis" type="text" disabled="disabled" value="111"> <input class="no" type= ...

What could be causing my page to suddenly disappear?

After saving my changes in the IDE and refreshing the browser to test the prompt() function in my index.js file, the entire page goes blank, showing only a white screen. I double-checked the syntax of my function and it seems correct. Everything else on th ...

"Utilize Node.js to generate a nested array structure with groupings

Here is an array data that I have: [ { tempId: 1, nik: '11002', employeeName: 'Selly Amaliatama', basic_salary: 3500000, id_component: 'AD0128114156', componentName: 'Tunjangan Maka ...

Adding an onload event in a function-based component without using a fetch call

Looking at the code snippet below for a React component: import React from "react"; import { Carousel } from "react-bootstrap"; function CarouselHome() { return ( <> ...