Using Express Router to serve and display static files in the public directory

The code snippet below is found in my index.js file:

var express = require('express');
var app     = express();
var PORT    = 3000;
var routes = require('./scripts/routes/routes');

app.set('views', './views');

app.set('view engine', 'pug');

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

app.use('/', routes);

app.listen(PORT, function() {
  console.log('App running');
});

In my routes.js file:

var express = require('express');
var router = express.Router();
var request = require('request');

router.get('/', function (req, res) {
  // rest of the code...
});

router.get('/subreddit/:subreddit', function (req, res) {
  // rest of the code...
});

module.exports = router;

In my views/index.pug:

html
  head
    link(href='app.css' rel="stylesheet")
    title Hello World!
  body
    div(class="container")
      h1= subReddit

      div(class="images_gird")
        each url in images
          div(class="image", style="background-image: url('"+ url +"')")

If I access localhost:3000 in my browser, everything functions correctly and displays a list of images from the subreddit earthporn.

But when I try to access localhost:3000/subreddit/cute, there seems to be an issue with the request for app.css. The logs indicate this unexpected behavior.

Upon inspecting the network tab in Chrome, I notice two sequential requests being made - first for

http://localhost:3000/subreddit/cute
, followed by another for
http://localhost:3000/subreddit/app.css
.

This peculiar behavior only occurs when accessing specific subreddits through the URL. I believe it might be related to how Chrome handles requests, as everything works fine when accessing the base URL localhost:3000.

Answer №1

This particular line

express:router dispatching GET /subreddit/app.css +83ms

is attempting to access https://www.reddit.com'+ app.css +'.json' but this request is incorrect, causing delays.

When in index.pug, consider using the complete URL for app.css

Answer №2

Appreciate the solutions. Managed to resolve it by adding /app.css in my index.pug

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

Explore our array of images displayed in an interactive gallery featuring clickable

I have a query I'm facing an issue with my code. Currently, I have a gallery that displays images perfectly. Now, I want to enhance it by showing a larger resolution of the image when clicked. However, when I add the href tag to link the images, they ...

The function of hasClass within an if statement appears to be malfunctioning

I'm struggling to figure out why my .hasClass function is not functioning correctly. I've implemented the Quick Search jQuery plugin, and below is the code I am using: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.mi ...

validation for grouped radio inputs

I'm having a small issue with appending error states. I have 7 radio inputs and after submitting, I see 7 error states under the group. Can someone assist me in modifying the code? <form class="register-form"> <div class="co ...

Exploring the capabilities of qTip2 integrated with jQuery Vector Maps (jqvmap)

Is there a way to disable the default tooltip in jqvmap and replace it with qTip2? Check out this example. Here's the jQuery code: jQuery('#vmap').vectorMap({ map: 'world_en', backgroundColor: null, color: '#ffff ...

Verifying Node.js request parameters against database field requirements

I am currently in the process of constructing a REST API using node, express, and MongoDB with mongoose. My goal is to implement validation for post requests. Below is an example of how I have defined a schema: var CategorySchema = new Schema({ name: ...

Having difficulty accessing node_modules directory in JavaScript

I am confused about how to access node_modules for JavaScript. Can someone provide an example of calling module.exports from a node_module folder after installing a package with NPM in Node.js? File tree structure: There is a folder named 'ethereum&a ...

What could be causing the issue of messages not displaying while incorporating connect-flash with res.locals in express.js and ejs templating?

Here are some snippets of code that may be useful. Connect-flash is designed to display messages on test1 and test2, but there seems to be an issue with displaying messages for test 3: user registration when all three tests are redirected to the same &apos ...

What is the main object used in a module in Node.js for global execution?

Node.js operates on the concept of local scope for each module, meaning variables defined within a module do not automatically become global unless explicitly exported. One question that arises is where a variable declared in a module file belongs in term ...

"Utilize Node.js to seamlessly stream real-time Instagram photos based on a designated hashtag

Does anyone know of a node.js library or solution that can automatically fetch Instagram photos in real-time based on specific hashtags? ...

When scrolling, apply a CSS class to a div element once it becomes visible on the

I'm in the process of developing a timeline feature for my website, and I am facing an issue where the addClass function is being applied to all sections, even those that are not currently visible on the screen during scrolling. If you would like to ...

Creating synchronization mechanisms for events in JavaScript/TypeScript through the use of async/await and Promises

I have a complex, lengthy asynchronous process written in TypeScript/JavaScript that spans multiple libraries and functions. Once the data processing is complete, it triggers a function processComplete() to indicate its finish: processComplete(); // Signa ...

Display the device model using Google Cloud Monitoring API

I've been utilizing a Node.js library to fetch metrics from my Google Cloud Compute Engine instances. You can find the library here. When creating a time series, the resulting data looks like this: { "points": [...], "metric": { "lab ...

Any tips or hacks for successfully implementing vw resizing on the :before pseudo-element in webkit browsers?

When using vw sizes on webkit browsers, a well-known bug can occur where they do not update when the window is resized. The typical workaround for this issue has been to employ javascript to force a redraw of the element by reassigning the z-index upon res ...

Tips on displaying a confirmation message upon a user clicking a checkbox

I am encountering an issue with displaying a confirmation message when a checkbox is clicked. The confirmation box pops up but does not carry out any action, like showing the text within the textbox after the user clicks OK. Any guidance on this matter wou ...

Guidance on toggling elements visibility using Session Service in AngularJS

After reading this response, I attempted to create two directives that would control the visibility of elements for the user. angular.module('app.directives').directive('deny', ['SessionTool', function (SessionTool) { ret ...

What are the key distinctions between DOCS and PSD base64 URLs?

My current challenge involves displaying a preview of attachments. I want to show an IMAGE SVG preview for image attachments and a PDF preview for PDF attachments, both based on their respective base64 formats. For example, I am currently using the split m ...

Experiencing consistent failures with the Node.js Passport Local Strategy

As I embark on my journey to understand user authentication in node, I am faced with the challenge of integrating Passport's LocalStrategy to add users to a Mongo database. In my attempt to follow a tutorial, things are not going as smoothly as expec ...

No data was returned in the responseText of the XMLHttpRequest

I am facing an issue where my XMLHttpRequest code is executing without any errors, but it always returns an empty responseText. Here is the JavaScript code that I am using: var apiUrl = "http://api.xxx.com/rates/csv/rates.txt"; var request = new XMLH ...

Explore an array of elements to find the correct objectId stored in mongodb

element, I am faced with a challenge of searching through an array of objects to find a key that contains nested object id for populating purposes. Exploring My Object { service: 'user', isModerator: true, isAdmin: true, carts: [ ...

Difficulty arises in AngularJS Material when attempting to access the same object value using ng-model and ng-change

I'm working with angular-material and facing an issue with an md-switch element. The model of the switch is determined by a value in a JavaScript object. However, I want to avoid directly changing the object value when the user toggles the switch. Ins ...