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

Tips for resolving the issue of the symbol ' displaying as &#39 in an Angular 2 application

I am currently working on an Angular application that makes API calls when a name displayed in a grid table is clicked. However, I have encountered an issue where names containing an apostrophe are being displayed incorrectly as &#39 instead. I managed ...

Using Vue's $emit method within a Promise

I am currently working on an image upload feature that is based on a Promise. Within the "then" callback, I am attempting to $emit an event named 'success'. Although my VueDevTools shows me that the success event has been triggered, the associate ...

Using Typescript to pass a property as one of the keys in an object's list of values

In my React Native project, I need to pass a string value from one component to another. The different options for the value can be found in the ScannerAction object: export const ScannerAction = { move: 'move', inventory: 'inventory&apo ...

What is the best way to change the orientation of a vector map?

Is there a straightforward method for rotating a vector-based map on CANVAS in order to integrate it into a browser navigation system? ...

Transmitting the User's Geographic Location and IP Address Securely in a Hidden Input Field

I'm looking to enhance my HTML form by retrieving the user's IP address and country when they submit the form. How can I achieve this in a way that hides the information from the user? Are there any specific elements or code additions I need to ...

Utilizing app.locals with .findOne in Mongoose: A Step-by-Step Guide

I am trying to locate the currently logged in user and save their information to app.locals for access in any view. In my server.js file, I have set up the following: app.use(ensureAuthenticated, function(req, res, next) { User.findOne({ _id: req.sessi ...

Struggling with Vue's Router Transition fade in/out effect not functioning as expected?

Question: I've implemented Vue's Router and it switches between components without any issues. However, I added a <transition name="fade" mode="out=in"> around it but the fade effect is not working as expected. Desired ...

Utilizing ReactJS to make an Ajax request

I am trying to transfer data to individuals and then display it using the array map function. export default class App extends Component { constructor(props) { super(props); this.state = { persons: [], }; } componentDidMount() { $ ...

Exploring the versatility of combining CSS classes with MUI 5 SX prop

Is there a way to use multiple CSS classes with the MUI 5 SX prop? I've defined a base class for my Box components and now I want to add a second class specifically for styling the text inside the Box. When I try to apply both classes like sx={styles. ...

Receiving information within an Angular Component (Profile page)

I am currently developing a MEAN Stack application and have successfully implemented authentication and authorization using jWt. Everything is working smoothly, but I am encountering an issue with retrieving user data in the Profile page component. Here ar ...

AngularJS uses variables defined by using curly braces like {{"message"}}

I am currently utilizing the following code snippet to monitor route changes: $scope.$on('$routeChangeStart', function (event, toState, toParams, fromState, fromParams) { //content $log.log(toState); } Whenever I print out "toState ...

Using Vanilla JavaScript and VueJS to smoothly scroll back to the top of a div when a button is clicked

I have a VueJS-based app that features a multistep form with a next button. You can check out the functioning of the app here: My current challenge is ensuring that once the user clicks the next button, the top of the following question becomes visible. I ...

Extracting a nested property from a JSON object without relying on the lodash get method

We have a sample json data: { "name": "app", "version": "0.1.0", "description": "Sample description", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "so ...

Issue with Material UI TextField and Redux Form integration

Having trouble with a textfield that I am trying to integrate with Redux Form. Here is how I have set it up: const renderTextField = props => ( <TextField {...props} /> ); Usage example: <Field id="searchCif" name="sear ...

How to have multiple versions of grunt coexisting on a single machine

I am involved in two different projects that have unique requirements for Grunt versions: Project A specifically needs Grunt v0.3.2 Project B requires Grunt v0.4.1 Both of these projects are managed in separate workspaces. Currently, I have Grunt v0.4. ...

Pair two arrays based on a specific key value

I'm currently facing a challenge where I need to associate two arrays of objects, and I could really use some help with this. Explanation : One array contains various reference products const array1 = [ {name: peanuts, referenceKey: 0}, {name: almon ...

Is it possible to move the res.send() outside of the function in node.js?

I currently have the following code: var server = http.createServer(function(req,res){ res.writeHead(200,{'Content-Type': 'text/html; charset=utf-8'}); var oo = require('/test.js'); oo(connection, function (e, res ...

The AngularJS Navbar is Bootstrapped

I'm currently working on a project where I need to make a bootstrap navbar show and hide html elements based on data retrieved from an angular controller. Below is the jade code snippet: div.navbar.navbar-fixed-top div.navbar-inner div.c ...

Adding code containing various Google Maps elements in a fresh browser window using JavaScript

I've encountered an issue while trying to create a new page with a Google map and title based on the button clicked. Interestingly, when I copy/paste the HTML in the "newhtml" variable into an actual HTML file, it works perfectly fine. However, it doe ...

Is it possible to install the lib ldap-client module in node.js?

I'm having trouble installing the lib ldap-client package in Node.js. To try and solve this issue, I consulted the following page: https://github.com/nodejs/node-gyp. In an attempt to fix the problem, I have installed python, node-gyp, and Visual St ...