Encountering a 404 error when attempting to access static files within a directory using Express Js

Organizing my static files has been a breeze with multiple directories. I have some static files in the client directory, while dashboard-related files are nested within the src directory. Here is how my directory structure looks:

/
|
client //housing static files and more
server //express server-side items like app, controller, models, etc
src //additional static files

With two separate Angular apps - one in the client folder and the other in src - my server-side routes are configured as follows:

app.route('/app/dashboard-v1').get(function(req,res){
        res.sendFile(path.join(__dirname, '../src', 'index.html'));
    });

    // Handling undefined asset or API routes with a 404 response
    app.route('/:url(api|img|src|auth|components|app|bower_components|assets)/*')
        .get(errors[404]);

    // Redirecting all other routes to index.html
    app.route('/*')
        .get(function (req, res) {
            res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
        });

My initial Angular app resides in app/dashboard-v1, with all other URLs being redirected to the second app.

While everything functions correctly in my second app, I encounter HTTP 404 errors for files in the first app. Commenting out the following line causes the index.html from the second app to be served instead of the expected 404 error:

//  app.route('/:url(api|img|src|auth|components|app|bower_components|assets)/*')
            .get(errors[404]);

The express configuration setup includes:

if ('production' === env) {
    // Production environment settings
} else {
    // Development environment settings
  }

Suspecting an issue with my routing, I wonder how to resolve this dilemma. In the index.html of my first app (app/dashboard-v1), I have included:

<base href="/src/" />

All internal links in my index.html are relative, such as this block from src/index.html (app/dashboard-v1 URL app):

<script src="vendor/angular/angular-animate/angular-animate.js"></script>
  <script src="vendor/angular/angular-cookies/angular-cookies.js"></script>

Examining the network console in my browser reveals that requests made to the server follow this pattern:

Request URL:http://localhost:9000/src/vendor/angular/angular-animate/angular-animate.js

The receive a 404 status code in the browser console, indicating potential issues with file retrieval.

Answer №1

Is the app running on the / directory in your example?

I believe you need to designate __dirname as the static folder

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

Alternatively, you can specify specific folders like so:

app.use("/public", express.static(__dirname + "/public"));
app.use("/public2", express.static(__dirname + "/public2"));

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

how can I convert div attributes into JSON format

I am working with the following div element: <div class="specialbreak"> This div has been saved in a JavaScript variable. My goal is to convert this div into JSON format so that I can easily access the class name. Although I attempted to use JSON ...

Express router failing to catch parameters in node application

So, here's the scenario: router.put('/user:resourceId', function(req, res) { User.findOneAndUpdate({resourceId: req.params.resourceId}, req.body, function(err, user) { if (err) res.send(err); ...

The jQuery closest selector seems to be malfunctioning when trying to scroll and focus on a specific class

My HTML code snippet is as follows: <div class="main"> <div class="sub-1"> <select> <option>1</option> <option>2</option> </select> </div> <div class="sub-2"> ...

Pug template experiencing issues with displaying images

I placed the images folder inside the views folder and provided the relative path to the images, yet they are not displaying on the html page. I have attempted various solutions such as moving the folder outside of views and using an absolute path, but not ...

How come the useEffect hook is causing re-rendering on every page instead of just the desired endpoint?

I am a novice attempting to retrieve data from a database and display it on the front-end using Axios, ReactJS, and TypeScript. My intention is for the data to be rendered specifically on localhost:3000/api/v1/getAll, but currently, it is rendering on all ...

inter-site requests & browser extensions

I'm currently working on developing a Firefox Addon using the new WebExtensions system. My goal is to: Extract specific text from a webpage (not owned by me) Evaluate it using an external website Display the result on the same page The issue I&apo ...

Encountering issues with Yarn Install during production build. Issue states: "Error - [email protected] : The engine "node" does not align with this module"

Currently facing an issue while deploying a ReactJS Project on the PROD environment. The previous command "Yarn install" was working fine, but now it's failing with an error message. The error that I'm encountering is: info [email protected ...

Is React the best solution for managing a lengthy list that requires constant data updates?

In order to display a long list with over 2000 entries that changes dynamically, I am utilizing react redux. Each second, at least one new row is added to the list data. My current approach involves mapping through the list data in the render method like t ...

Having trouble with Vue.js implementation of Bootstrap tab navigation?

I am currently working on a vue.js application that consists of 2 routed components. I recently attempted to integrate a bootstrap tab navigation into the first component, but unfortunately, the tab contents are not being properly displayed. <templat ...

Challenging multiple layers of ng-repeat

https://jsfiddle.net/n4qq4vxh/97/ As part of my project, I am creating tables that describe the packages selected when customizing a car. The dark grey represents the entire package, such as the luxury package, while the lighter grey indicates the items c ...

Modify the Google Maps icon based on the type of data within an array dynamically

Being new to the world of JavaScript, I've been given the task of converting an old jVector map to the Google Maps API. Surprisingly, I think I'm making good progress! I've successfully populated the map with the right markers in their assig ...

What is the process for loading JavaScript along with its dependencies?

Imagine a scenario where I have script A that loads another script B: $.getScript('B.js', foo); Now, what if script B also loads an additional script? In that case, I want the function foo to be executed only after both B and its loaded script ...

Break down one object into an array consisting of multiple objects

I have a single object in the following array: [{"IP_Address":"33.4.160.5","originEmailAddress":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f050e020a1c2f18060303061c410c0002">[email protected]</a>"}] I am lookin ...

Effective ways to position images within a card alongside a changing title

I have a requirement for displaying multiple cards with dynamic titles fetched from the backend. The challenge is to align images in a row regardless of the title length, ensuring alignment based on the longest title. Below is an illustration of what I am ...

Updating an existing value with a cascading dropdown list

My JavaScript code dynamically populates a dropdown list called District based on the selection made by the user in another dropdown list called Department. Here is the snippet of the code: Firstly, I populate the Department dropdownlist and add a ' ...

Navigate between pictures using hover in jQuery

I am working on creating a feature where images cycle through individually every 2 seconds, but switch to the right image when its associated link is hovered. So far, I have managed to make the images show up on hover, but I am struggling with getting them ...

Dynamically loading Jquery tabs in AngularJS can enhance user experience and

I need to implement a feature that loads tabs from an array using AngularJS. $scope.hods = [ { leader_id: 1000321, staff_id: 1000321, longname: "Ooi Kok Hong", username: "ANDREW", team_role: "HOD", importance: "1", active:true }, { leader_id: 100 ...

typescript is failing to update CSSRule with the newly assigned background-color value

I am currently working on dynamically changing the CSS style (specifically background-color) for certain text on a webpage. To achieve this, I have been attempting to modify CSSRule by accessing the desired CSSRule based on selectedText. Here is the code s ...

What is the process for transmitting a base64-encoded image from AngularJS to Laravel using the POST method?

Hey there! I am a beginner in Laravel and AngularJS. I have a question about sending an uploaded image (converted to base64) to Laravel. This is how my HTML code looks: <input type="file" class="upload upload-button" fileinput="fileinput" filep ...

Encountering a "file or directory not found" error during the installation of ply using

I recently stumbled upon an interesting project for testing Rest APIs. I was in the process of installing ply from https://github.com/ply-ct/ply npm install ply-ct --save-dev Encountered this error, wondering if anyone has a solution npm WARN saveError EN ...