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

Using AJAX to set a session variable in PHP

Upon clicking a div, this JavaScript function is executed: $('.test').click(function(e) { e.preventDefault(); $.ajax({ url: 'ajax.php', type: 'POST', data: {"id": "<? ...

Codemirror - Advanced Auto-Suggest Feature with Separator

Can a separator be easily added in the hints/autocomplete addon? This separator would help transform the suggestion box to look like: f1 f2 f3 --- var1 var2 ...

Circular movement in ThreeJS within a specified duration

I am currently working on creating a circular motion for an object within a set time frame. This project involves designing a clock with smooth motion. Instead of simply updating the position to fixed coordinates every time .getSeconds() changes, I aim t ...

Rendering based on conditions with a pair of values

I am trying to render my component only if the id is equal to either 15 or 12. My current approach is not working as expected, it only renders the component when I check for one id at a time, but I need to check for both. {query_estate_id === 15 || q ...

The VueJS component fails to load on the webpage

Here is my Vue.js component code that I am having trouble with. Despite its simplicity, it does not load correctly: Vue.component('my-component', { template: '<div>{{ msg }}</div>', data: { msg: 'hello' ...

Heroku's Express server encountered a 503 error, stating that the service is currently unavailable

I set up a server on heroku without a database, and all the GET requests are working fine. However, when I try to make a POST request from a different heroku domain, I am receiving an error: 503 "service unavailable". Has anyone encountered this issue befo ...

Anticipated semicolon in the JavaScript file

I recently came across the dialogflow demo as a reference. However, I encountered an error stating 'semicolon expected' at the method sendTextMessageToDialogFlow. How can I resolve this issue? Below is the code snippet: router.post('/dialo ...

Is CefSharp compatible with JavaScript promises?

I noticed that when I run the JavaScript code below in the console of my browser, it works perfectly fine. However, when I try to use this code in CefSharp, it returns null. I am currently using CefSharp version 100.0.120-pre. Does CefSharp 100.0.120-pre s ...

Is there a way to attach an event for multiple arithmetic operations to a checkbox?

My form includes 4 checkboxes for different mathematical operations. <form action="" method="POST"> Select number of questions: <input type="number" name="que" value="que"> <br> <br> Select number of series: <select name="sel ...

Guide to embedding a component within another component using route based rendering

My routing configuration looks like this: <Provider store={store}> <BrowserRouter> <Route path="/" component={App} /> <Route path="/customers" component={Customers} /> <Route path="/tickets" componen ...

How should one correctly trigger an event in Google scripts?

When it comes to calling in the active elements, I have been using event.source.getActive and SpreadsheetApp.getActive. However, I have noticed that I sometimes interchange them in my script and face issues. So, I am unsure about which method is more app ...

AWS Amplify-hosted Nuxt applications are resilient to errors during the build process

My website is built using Nuxt js and hosted on AWS Amplify. I've encountered a major issue where the website still gets generated successfully even when there's a failure in the nuxt generate command (like a JavaScript error in my code). Below i ...

How can I show only the final four digits of an input field using Angular Material and AngularJS?

As a newcomer to Angular Material and Angular JS, I am striving to create an md-input field that displays only the last 4 digits in a masked format, such as "********1234". While my experience is currently limited to using md-input password fields where ...

The footer should remain at the bottom of the page without being permanently fixed

Is there a way to keep the bootstrap footer at the bottom without fixing it in place? In the code example below, the footer should always appear at the bottom. The white space after the footer should come before it. Using sticky-bottom achieves this, but ...

Before I press enter, what kind of function is evaluated by the Node.JS REPL?

It's interesting how in the Node.JS REPL, the result of the current expression sometimes gets evaluated before hitting enter, which raises questions. I find it puzzling: How does Node.JS determine if I intended to evaluate it or not? Simple calculati ...

Unable to send headers to the client in expressjs as they have already been set

After successfully logging in, I am trying to redirect to another page but keep encountering the error message "Cannot set headers after they are sent to the client". I understand that I need to place the res.redirect method somewhere else in my code, bu ...

Is it possible to transform all values in arrays to 0s in JavaScript/p5.js during the copying process?

I’m struggling with a simple code where I want to store an array of arrays containing FFT audio data. It seems like there might be a JavaScript issue because when I try to push the array into another array called spectrums, all the values inside spectr ...

Inability to update Vue.js component data even after a successful GET request

I am encountering an issue with a component that initially contains a default object, and then fetches a populated object via a GET request upon creation. Despite successfully updating this.profile within the method, the changes do not seem to propagate ...

Utilizing production and development configuration files in Angular and JavaScript with Webpack

I'm currently working with Webpack and Angular, trying to find a way to inject/use variables based on whether it's in development or production mode. Although I have Webpack set up to detect the environment (prod or dev), I am facing an issue wi ...

What steps can a web developer take to view user console errors?

Is there an effective method for a web developer to receive notifications of console errors logged by other authorized users? I am currently working with Express, Passport, and MongoDB. These errors may occur on either the client or server side. One approa ...