Express.js does not display console.log messages while routing

Just starting to explore Express and its middleware functions.

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

app.get('/', function(req, res) {
   res.send('id: ' + req.params.id + ' and name: ' + req.params.name);
});
var things = require('./things/things.js');

//both index.js and things.js should be in same directory
app.use('/things', things);

//Simple request time logger
app.use('/',function(req, res, next){
   console.log("A new request received at " + Date.now());

   //This function call is crucial for further processing of the current request
   //and routing it to the next middleware function.
   next();
});

app.listen(3000);

I'm experimenting with middleware functions and trying to output a message on localhost:3000, but nothing shows up in my console. Any idea what I might be overlooking?

Answer №1

The issue arises because Express processes requests by following the order of declaration for both middleware and route handlers. If a middleware or handler is able to respond to a request, any subsequent matching middleware or handlers declared later will not be executed.

This situation is present in your case, where the middleware is defined after the route handlers.

To resolve this, try reordering your middleware to come before the route handlers:

app.use('/',function(req, res, next){
   console.log("A new request received at " + Date.now());
   next();
});

app.get('/', function(req, res) {
   res.send('id: ' + req.params.id + ' and name: ' + req.params.name);
});

var things = require('./things/things.js');

app.use('/things', things);

Answer №2

To start, it's important to review the file structure. If index.js and things.js are located within the same folder, you will need to update the require function to

var things = require('./things.js');

After that, double-check that you are checking in the correct location. The message from console.log() will only show up in the terminal window where you started the express server, not in the browser console.

Answer №4

When using the get method, the proper way to define parameters 'id' and 'name' is as follows:

app.get('/:id/:name', function(req, res) {
   res.send('id: ' + req.params.id + ' and name: ' + req.params.name);
});

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

Extracting the chosen content from a textarea using AngularJS

Greetings! I am currently experimenting with an example that involves displaying values in a text area. You can find the code on Plunker by following this link: Plunker Link <!DOCTYPE html> <html> <head> <script src="https://aj ...

Modifying an image's height and width attributes with jQuery and CSS on click action

I'm currently developing a basic gallery using HTML, CSS, and jQuery. The objective is to have a larger version of an image display in a frame with an overlay when the user clicks on it. While this works flawlessly for horizontally-oriented images, ve ...

Troubleshooting: Issues with Custom Image Loader in Next.js Export

I'm encountering a problem while attempting to build and export my Next.JS project. The issue lies with Image Optimization error during the export process. To address this, I have developed a custom loader by creating a file /services/imageLoader.js ...

Tips for displaying HTML elements using JSON data in React?

My goal is to dynamically render HTML elements based on JSON data using a React class that takes objects and generates a list of divs. The values inside the divs correspond to the first value in each object within the JSON. Here's an example of the J ...

What is the best way to sequence the functions in an AJAX workflow?

I'm currently working on optimizing the execution order of my functions. There are 3 key functions in my workflow: function 1 - populates and selects options in a dropdown using JSON function 2 - does the same for a second dropdown function 3 - ...

Removing an element from an array in a Laravel database using AngularJS

I am currently working on a project where I need to delete an item from my Laravel database, which is a simple Todo-List application. To achieve this, I have implemented a TodosController in my main.js file using AngularJS and created a Rest API to connect ...

Unable to save data in local storage

I'm enhancing an existing chrome extension while ensuring a consistent style. I am looking to implement a new feature, and I have written a script that saves the user's selection from the popup and sets a new popup based on that choice going forw ...

Validating minimum and maximum values with Angular 2 FormBuilder

I am currently developing a form using Angular 2 Formbuilder and I want to ensure that users can only input positive values into the amount field (with a minValue of 0 and maxValue of 100). How can I go about implementing minimum and maximum value validati ...

Is there a way to resolve this issue? (An error occurred: TypeError - res.json is not a valid function)

When attempting to add an object to my MongoDB database const response = await fetch("/api/contact", { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json", }, }); I encounter the error message ...

Achieve a Smooth Transition: Utilizing Bootstrap 3 to Create an Alert Box that Fades In upon Click and Fades Out

Incorporating AngularJS and Bootstrap 3 into my web app, there is an "Update" button that saves user changes. Upon clicking the "Update" button, I aim to trigger and display bootstrap's alert box with the message "Information has been saved," followed ...

What is the best way to redirect using Express, EJS, and external JavaScript files?

I am facing an issue with my login form. After collecting the user's email and password, I use JavaScript fetch to send the data to Express. Then, I validate the inputs using express-validator. However, when I try to redirect to another page using res ...

Which Hosting Option is Best for Hosting a NodeJS app on Namecheap: Shared Hosting or VPS

I am currently running an Ecommerce Node.js application with NuxtJS on the frontend and NestJs/Node.js on the backend. I'm contemplating whether Shared Hosting or VPS Hosting would be more suitable for hosting this app, particularly on Namecheap or an ...

Learn the steps to invoke a JavaScript function from a <td> element within an ng-repeat loop

How can I call an Angular function inside ng-repeat td and replace the value from the function with the value in the td element? The code snippet provided below is not functioning as expected. Instead of getting the date, the same getCSTDateTime function i ...

Receiving a 404 error when attempting to update row values using an id with sequelize

Currently, I am working on a project using nodeJS, expressJS and reactJS. While I can access each data's id by clicking the edit button, I am facing issues with updating the data. Every time I click the button, a 404 error is displayed in the console. ...

The search filter in Angular is limited in its ability to search through the entire table

I am facing an issue with the search filter in my table. Currently, it only searches records from the current page but I need it to search through the entire table. How can I modify it to achieve this? <input type="text" placeholder="Search By Any..." ...

What's the reason behind ng-click only functioning with a function and not an assignment within this specific directive?

I am currently working on creating a dynamic table using an array of objects that can be sorted by clicking the headers. I have a specific question regarding how the sorting feature is implemented. let myDirectiveTemplate = ` <table class="directiveTab ...

What is the best way to generate a new div element when the content exceeds the preset height of the current div?

CSS .page{ width: 275px; hight: 380px; overflow: auto; } HTML <div class="page">dynamic text</div> Is there a way to automatically create new div elements when dynamic text overflows past the fixed height of the init ...

What is the best way to incorporate user-provided values into a dynamic URL?

I am trying to create a feature where users can input a value and then click a button that will take them to a URL tailored to their entry. Here is my current code, but I am facing an issue - the user_input data does not seem to be passed to the URL when ...

Expanding Vue JS Vuetify Panels in a V-for Loop to Reveal Multiple Panels

When pulling data from a database and looping through it in the DOM using a "v-for" loop, I encountered an issue with Vuetify expansion panel components. The problem is that when a user clicks to open one expansion panel, it ends up opening all other panel ...

Accessing a Child Component Function in Material UI

Utilizing the Material UI framework, I am constructing an application with React. Included in this application is a Dialog feature that permits users to modify various information about an object (referencing the code below). The dialog consists of two but ...