An unexpected 404 error occurred when trying to import external scripts in

I am currently attempting to import an Angular module from a separate file.

Here is the content of my app.js

var app = angular.module('app', ['ngRoute']);
app.controller("TodoController", function($scope) {
  $scope.players = ["Tom", "Dick", "Harry"];
});

This is my index.html

<html ng-app="app">
    <head>
        <title>Hello Angular!</title>
    </head>
    <body ng-controller="TodoController">
        <input type="text" name="" ng-model="name"> {{name}}

        <ul>
            <li ng-repeat="player in players">
            {{ player }}
            </li>
        </ul>

        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular-route.min.js"></script>
        <script src="scripts/app.js"></script>
    </body>
</html>

I am leveraging express with node. This is my server.js

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

var port = process.env.PORT || 5000;

app.get('/', function(req, res){
  //res.sendfile('./index.html');
  res.sendFile('index.html', { root: path.join(__dirname) });
});

app.listen(port);
console.log('Express app is listening on : ' + port);

Upon execution, I encounter the http://localhost:5000/scripts/app.js 404 (Not Found) error.

The code functions correctly when all placed directly in the index.html.

The File Structure resembles the following.

-- index.html
-- server.js
-- scripts
    -- app.js 

Answer №1

After some troubleshooting, I finally found the solution to the problem. It turns out, the issue was related to Serving static files in Express, as pointed out in a helpful comment. I made the necessary adjustments to the server.js file to fix this.

app.use(express.static('public'))

Additionally, I created a 'public' folder and placed app.js inside it.

Here is how my updated code looks:

public/index.html

<html ng-app='app'>
    <head>
        <title>Hello Angular!</title>
    </head>
    <body ng-controller="TodoController">
        <input type="text" name="" ng-model="name"> {{name}}

        <ul>
            <li ng-repeat="todo in todos">
                <input type="checkbox" ng-model="todo.completed">
                {{todo.title}}
            </li>
        </ul>

        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular-route.min.js"></script>
        <script type='text/javascript' src="app.js" charset="UTF-8"></script>
        <script type='text/javascript' src="app/controllers/TodoController.js" charset="UTF-8"></script>
    </body>
</html>

Server.js

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

var port = process.env.PORT || 5000;

app.get('/', function(req, res){
  res.sendFile('index.html', { root: path.join(__dirname, 'public') });
});

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

app.listen(port);
console.log('Express app is listening on : ' + port);

public/controllers/TodoController.js

app.controller('TodoController', ['$scope', function ($scope) {
    $scope.todos = [
    { title: 'Learn Javascript', completed: true },
    { title: 'Learn Angular.js', completed: false },
    { title: 'Love this tutorial', completed: true },
    { title: 'Learn Javascript design patterns', completed: false },
    { title: 'Build Node.js backend', completed: false },
    ];
}]);

public/app.js

var app = angular.module('app', []);

The updated file structure looks like this.

-- public
  -- app
    -- controllers
      -- TodoController.js
  -- app.js
  -- index.html
-- server.js
-- package.json

Answer №2

With only the http://localhost:5000/ route exposed, you can see that it renders the index.html file.

app.get('/', function(req, res){
  //res.sendfile('./index.html');
  res.sendFile('index.html', { root: path.join(__dirname) });
});

Attempting to access any other path will result in a 404 error. Direct access to http://localhost:5000/scripts/ is not allowed. To access scripts, add the following line in your server.js file:

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

Here is the updated code for your server.js:

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

var port = process.env.PORT || 5000;
app.use(express.static(path.join(__dirname, 'scripts')));
app.get('/', function(req, res){
  //res.sendfile('./index.html');
  res.sendFile('index.html', { root: path.join(__dirname) });
});

app.listen(port);
console.log('Express app is listening on : ' + port);

Now, accessing http://localhost:5000/scripts/app.js should no longer result in a 404 error. Not only app.js, but any file within the scripts folder can now be accessed.

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

Exploring the use of global variables in React

Welcome to my React learning journey! I've encountered an issue while trying to access a global variable exposed by a browser extension that I'm using. Initially, I attempted to check for the availability of the variable in the componentDidMount ...

Searching an array object inside another array object using JavaScript/AngularJS

Here is my issue: I am facing a situation where I have two Array objects as follows var array1 = [{ "id": 1, "name": "potatoe", photo="photo"}, {"id": 2, "name": "budget"}] var array2 = [{ "id": 1, "name": "potatoeModified"},{ "id": 3, "name": "UhOhA ...

Limiting decimal places in Angular filter

Is there a way to create a custom filter that takes an input, specifies the maximum number of decimals to display, and returns a string formatted according to locale rules? Input(number) Output for 1 decimal Output for 2 decimals 1.01 1 ...

Discovering the country associated with a country code using ngx-intl-tel-input

In my application, I am trying to implement a phone number field using this StackBlitz link. However, I have observed that it is not possible to search for a country by typing the country code (e.g., +231) in the country search dropdown. When I type a coun ...

Customized style sheets created from JSON data for individual elements

One of the elements in the API requires dynamic rendering, and its style is provided as follows: "elementStyle": { "Width": "100", "Height": "100", "ThemeSize": "M", "TopMargin": "0", " ...

A 403 error is thrown by the Microsoft Graph API when attempting to delete the authentication method known as "Microsoft Authenticator"

I'm trying to remove a user's Microsoft Authenticator Authentication Method (#microsoft.graph.microsoftAuthenticatorAuthenticationMethod) from their list of authentication methods, but I keep getting a 403 Forbidden error. Below is the code snip ...

Attempting to modify text using the header parameter has proven to be ineffective

pages/_middleware.ts import { NextRequest, NextResponse } from 'next/server'; const isMobile = (userAgent: string) => /iPhone|iPad|iPod|Android/i.test(userAgent); const propName = 'x-rewrite'; enum Device { desktop = 'no& ...

Leveraging jQuery to interact with MySQL database in PHP Laravel framework

I seem to have hit a roadblock with my database, which is quite intricate. Here's the breakdown of the tables used for the questions: product - contains product details such as shoes productattribute - houses different variations of products like bl ...

When using Python Selenium, we can see JavaScript in the view page source, but inspecting elements reveals the

I'm currently facing a challenge in accessing links to attachments for a web automation project. The issue lies in the fact that while I can view the HTML Code (divs and tables) when loading the webpage via Chrome and inspecting element, all I see in ...

What is the best way to implement transition effects while toggling between light mode and dark in tailwind 2.0?

Currently, I am working on a small project utilizing tailwindCSS and have decided to incorporate a dark mode feature. To achieve this, I created a button that toggles the dark class in the html tag. However, upon testing the functionality, I noticed that t ...

Having trouble transmitting a file from the frontend to the server in your MERN project?

Struggling to transfer an image file from the React frontend to the server and encountering issues with sending the file: Below is the front end code snippet: useEffect(()=>{ const getImage=async ()=>{ if(file){ ...

"Potential Memory Leak Issue: Assigning dataUrl to img.src May Cause Memory

Here is a demonstration of a simple test case where setting an img tag's src to different dataUrls leads to memory leakage. It appears that the image data is not unloaded even after the src is changed. <!DOCTYPE html> <html> <head> ...

React component will automatically rerender if the cache is disabled in the Chrome browser

In my React application, I am utilizing 'react-image-pan-zoom-rotate' to display images. Visit the GitHub repository here The image I am displaying is sourced from an external service and passed to both libraries for rendering. Lately, I have ...

Can we gather all elements with the 'required' attribute and assign them to a single event in JavaScript?

I am facing an issue with a button that triggers a function when clicked. The problem is that even though the required fields are not filled, the function still gets executed. This is how I have set it up: $('#SubmitButton').click(function() { ...

"Embrace the powerful combination of WinJS, Angular, and TypeScript for

Currently, I am attempting to integrate winjs with Angular and TypeScript. The Angular-Winjs wrapper functions well, except when additional JavaScript is required for the Dom-Elements. In my scenario, I am trying to implement the split-view item. Although ...

The ng-repeat function is iterating through the array multiple times

Using ng-repeat to bind the same array multiple times. JavaScript : $scope.currentitem = item; $scope.currentitemCategory = $scope.currentitem.category.split(','); console.log($scope.currentitemCategory); HTML: <div ng-repea ...

Can one utilize Javascript to write in plain text format?

Currently, using JavaScript I have a plain text containing data that is displayed within my form tags. Everything is functioning correctly, but now I need to update the values inside the code of my form tags in order for the changes to also be reflected in ...

JavaScript Astro file not triggering window.onload event

I need assistance with my Astro components in my App: apps/myProject libs/components/header Within the header.astro component, I have a script that should execute once the entire page is rendered: <script is:inline> console.log('hello!' ...

Avoid the sudden change in page content when using Router.Navigate

When the link below is clicked, the current page jumps to the top before proceeding to the next page. <a href="javascript:void(0);" (click)="goToTicket(x.refNo, $event)">{{x.ticketTitle}}</a> component.ts goToTicket(refNo, e) { e.prev ...

What is the best way to transfer information between different pages in an HTML document?

I am facing a specific requirement where I must transfer form data from one HTML page to another HTML page. The process involves a total of 5 pages, with the user entering data in the following order: 1st page: Name 2nd page: Weight 3rd page: Height 4t ...