Issue: Node.js Express unable to access static files when the route is nested more than one folder level deep.Resolution

Before we delve into the question, let me share with you the folder structure of my node.js express app:

/home
    server.js
    index.html
    /app
        /routes
            public.js
    /public
        /css
            main.css

In my server.js file, here is what I've implemented:

// ROUTING FOR STATIC CONTENT
var public_dir = __dirname + '/public';
app.use(express.static(public_dir));

// INITIALIZE ROUTER
var public_router = express.Router();

// IMPORT PUBLIC ROUTES
require('./app/routes/public')(public_router, public_dir);

// REGISTER ROUTES
app.use('/', public_router);

This is the contents of /app/routes/public.js:

var path = require('path');

module.exports = function(public_router, public_dir) {

    public_router.get('/new', function(req, res) {
        res.sendFile(path.join(public_dir, 'index.html'));
    });

    public_router.get('/popular', function(req, res) {
        res.sendFile(path.join(public_dir, 'index.html'));
    });

    public_router.get('/popular/today', function(req, res) {
        res.sendFile(path.join(public_dir, 'index.html'));
    });
}

Within index.html, I reference the css file as follows:

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

The issue at hand:

Upon visiting mydomain.com/new and mydomain.com/popular, the css file loads correctly and the page displays properly. However, when accessing mydomain.com/popular/today, the css file fails to load correctly. Upon inspecting in Chrome dev tools, it seems like the browser is attempting to fetch the css from the popular folder, which is incorrect.

I welcome any ideas or suggestions that could help resolve this matter. Thank you in advance!

Answer №1

To ensure proper file linking, modify the code from

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

By adding a forward slash before the CSS file path, the browser will begin searching from the root directory instead of relying on relative paths.

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

Retrieving the value of a submit button within the `onSubmit` event handler in a React application

In my usual process, I typically handle the form submission by utilizing the onSubmit handler. <form onSubmit={e => { ... } }> <input ... /> <input ... /> <button type="submit">Save</button> </form> ...

What is the method for individually extracting values from HTML using class li?

Is there a way to extract each value from the HTML within the li class separately? I have tried various methods but none have been successful. Can anyone provide a solution? Here is my JavaScript code: $(document).ready(function() { $(".list-grou ...

Angular findIndex troubleshooting: solutions and tips

INFORMATION = { code: 'no1', name: 'Room 1', room: { id: 'num1', class: 'school 1' } }; DATABASE = [{ code: 'no1', name: 'Room 1', room: { id: 'num1', ...

Tips for automatically refreshing a page after submitting a form

I have a template with two components - a filter and a request to the API. I am wondering if it's possible to update the values of the request component after submitting the filter. On the main page, the request component has default values. When a u ...

JavaScript Simplified Data Sorting after Reduction

I have extracted data from a JSON file and successfully condensed it to show the number of occurrences. Now, my next step is to arrange these occurrences in descending order, starting with the most frequent. To illustrate: var myData = [{ "datapo ...

Modifying SVG outline colors using CSS

Why is the CSS color: #ffffff not applying to my SVG? This is how it currently looks: https://i.sstatic.net/qh7ng.png This is how I want it to look: https://i.sstatic.net/6tLo5.png Surprisingly, changing currentColor to #ffffff in the SVG itself works ...

The compatibility issue between Jquery highlight and show more/less function is causing them to malfunction when used

I am facing an issue where, while trying to search for a specific word to highlight it, the "show more" button closes and only displays the text prior to clicking the button. How can I ensure that the expanded content remains open while searching for a wor ...

Vue.js navigation guards, restrict access to all unauthorized routes, grant entry to specific routes upon successful authentication

I'm currently working on implementing a navigation guard in Vue.js with a specific logic: I want to restrict access to all routes that require authentication and redirect users to the login page if they are not authenticated. The only exception is the ...

Hover to stop menu movement

Can someone help me achieve a similar menu hover effect like this one? I'm trying to create a menu with a hold/pause effect on hover, specifically in the section titled "A programme for every vision". The goal is to navigate through the sub menus smo ...

What is causing the chat-widget to display a null value for the style read property?

Could someone assist me with hiding the Widget-chat? I keep getting an error that the property of style is null. Any help would be greatly appreciated. Thank you in advance. document.getElementById("chat-widget").style.display='none'; ...

Is it possible to create a fading effect on an image using a border-radius of 50%?

Struggling with fading out an image that's circular in shape due to the border-radius: 50%. <section id="main"> <h1>Non-Important-Text</h1> <h4> it's all fun and games until you can't find a damn sol ...

Can you explain how the interactive notification on stackoverflow is generated when you are responding to a question and someone posts a new answer?

Have you ever been in a situation where you're writing an answer to a question, but then someone else posts their response and a popup appears notifying you of the new answer? I'm curious about how that whole process works. It seems like the answ ...

Enhance Your Form Validation with jQuery UI Dialog Plugin

Currently, I am utilizing the bassistance validation plugin for form validation. I have set up a pop-up modal dialog box to contain a form that requires validation, but for some reason, the form is not getting called. I have checked all my ID's and re ...

What is the best way to obtain the id of a selected row using JavaScript?

I'm attempting to utilize the JavaScript function below to extract a specific cell value from a jqgrid upon clicking. Within the following function, #datagrid refers to the table where the jqgrid is located. $("#datagrid").click(function ...

Using npm properties reader to access a key with multiple suite values from a properties file in Protractor

Recently, I had to find a way to store some data outside of the standard conf.js file. To tackle this requirement, I decided to use the properties-reader node module. However, I encountered some issues when trying to access certain key values. Below are e ...

In a post request, ExpressJS fails to receive the response

Can you assist me with the following issue I am facing: I have set up an API on my localhost to act as a connection between my front-end and database. Using Express in my front-end server, when I submit a form, the data gets stored in the database and th ...

Angular 2's Implementation of Hierarchical Dependency Injection

I'm encountering a problem with my Angular 2 application. I have a root component, AppComponent, where I've injected a service called ProductService. Now, I am trying to resolve this service in one of the child components, ProductList, but I keep ...

The frozen first column in a CSS table does not have consistent height with the rest of the row

Having trouble with freezing the first column of a table and aligning the height of the first cell with the rest of the row? Check out the issue in the image below: https://i.sstatic.net/v5xHU.png For a live example, you can also visit this jsfiddle link ...

Issue with redux causing component to not re-render after state change

I've been encountering an issue where I have to refresh the page every time I try to delete a post. The store updates after the refresh, as confirmed by the React devtools in Chrome. I'm keen to understand why this is happening. For context, I h ...

Tips for displaying a prompt in the browser window using a blob response from the server

I am facing an issue with the exportChallenges button on a kendo grid in my web application. The button is supposed to export grid data to excel by using an AngularJs factory. However, when I receive the rest service response as a Blob from the server side ...