function for app.get callback in express.js

Hey there, I'm a bit puzzled by the syntax of the get route function because there seem to be two versions. Here's an example of some code:

First one:

app.get('/users', function(req,res){
     ...
});

Second one:

app.get('users/:name', function(req,res,next){
     ...
     if(users[req.params.name])
      ....
     else
         next()
});

I'm confused about the purpose of the 'next' function in the second one and why it isn't necessary in the first one.

Thanks!

Answer №1

Consider taking a step back and viewing express as a middleware stack, much like a literal stack.

With a series of app.use, app.get, and app.post calls, you create a chain of middleware functions. When a request is received, express identifies which middleware functions match the URL pattern and calls the first one, passing along a reference to the next in line. This is how separate, independent middleware objects become interconnected.

For instance, there are middleware functions that parse query strings into an object stored in req.query, handle cookie header parsing, and provide access logging. These functions are linked together in a cohesive chain, with each passing control to the next by invoking next().

app.use(express.logger());
app.use(express.responseTime());
app.use(express.compress());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.cookieParser());
app.use(express.session());
app.use(i18n.handle);
app.use(app.router);

The reason routes typically don't use next is because they often mark the end of a middleware chain. After reaching a route, there's usually no further processing needed.

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

Steps to store user input into an array and subsequently combine the stored input:

I am currently working on a form that consists of two text boxes: Task and Description. My goal is to be able to log the input from both boxes and save it via a submit button. For example: Task: do laundry Description: do a buttload of laundry (idk lol) I ...

Trapping an iframe refresh event using jQuery

I am trying to dynamically load an iframe using jQuery. Here is my code: jQuery('<iframe id="myFrame" src="iframesrc.php"></iframe>').load(function(){ // do something when loaded }).prependTo("#myDiv"); Now, I need to capture th ...

Creating scalable React applications

Can you provide insights on the scalability of React Apps? What recommended approaches are typically employed to effectively handle and generate scalable states in web applications using Reactjs? * ...

Leveraging the express.static middleware

Both of the code snippets above achieve the same result of serving index.html at localhost:3000/ once the server is up and running. Difference in Approach: express.static const path = require('path'); const express = require('express' ...

Creating a dynamic directive in AngularJS: Learn how to add or remove it from the DOM based on specific conditions

Suppose I have a customized modal directive that looks like this: return { restrict: 'E', templateUrl: 'modal.html', scope: { modalContent: "&", modalOpen: "&" } } And in the HTML: <ng-modal modal-content="co ...

Changing color based on AngularJS condition using CSS

My HTML code looks like this: <div> <i class="glyphicon glyphicon-envelope" style="margin-top: -50px; cursor:pointer; color: #1F45FC" ng-click="createComment(set_id)"> </i> Route <center> ...

What is the process for playing an audio file on a mobile device?

Recently, I encountered an issue with a jQuery statement that plays a created audio file. Strangely, the file plays correctly on my computer but not on my mobile phone. Despite max volume settings, there is no sound when trying to play it on the mobile dev ...

Issue with handling keypress event and click event in Internet Explorer

Below is the HTML code for an input text box and a button: <div id="sender" onKeyUp="keypressed(event);"> Your message: <input type="text" name="msg" size="70" id="msg" /> <button onClick="doWork();">Send</button> </di ...

An error occurred with Express and Passport: ['ERR_HTTP_HEADERS_SENT']

Currently, I am diving into an ebook tutorial and have encountered a roadblock in a particular piece of code. The code is designed to take a username and password in JSON format through Insomnia or Postman, and it should return a login success cookie. Howe ...

There is an issue with block tag error when trying to render Markdown in Nunjucks

When attempting to render Markdown using Nunjucks markdown in a file, I encountered a block tag error during the rendering process. I believe the issue lies in not properly registering the block tag, but as a newcomer to rendering in express and Nunjucks, ...

The way in which notifications for updates are displayed on the Stack Overflow website

Could someone shed some light on how the real-time update messages on this platform are created? For instance, when I am composing a response to a question and a new answer is added, I receive a notification message at the top of the page. How is this fun ...

Capable of retrieving the identification number but incapable of executing a POST request

After successfully retrieving the ID using the router, I encountered an issue when trying to confirm the change of agent status on the retireagent HTML page by clicking the submit button. The error message displayed is "ID is not defined". I am seeking ass ...

Implementing a separate detail view in Vuejs

I am currently working on a page with multiple cases. When I click on a case, the details for that case appear on the same page. Here is a screenshot of how it looks: As you can see in the screenshot, there are two cases listed - "ublox" and "test case". ...

Is it appropriate to use localStorage in the createSlice "reducers" parameter of React Redux Toolkit?

I'm working on implementing a basic favorites list feature. Currently, there is no backend functionality in place so this will be stored in the localStorage. It might potentially switch to an API call in the future. Would it be considered acceptable ...

Unable to establish connection with NodeJS Express Server

I'm having trouble connecting to my Express server. I've set up my Axios connection to the front end, but it doesn't seem to be reaching the endpoint. Even when I try to connect directly from the browser, it just keeps spinning. The server d ...

Seeking suggestions: Integrating a Redux-create-react-app into an Express backend server-side rendered application

Greetings, as a newcomer to React I have a design query that I would like to discuss. I am working on an application that bears resemblance to scratch (scratch.mit.edu), featuring a highly interactive program allowing users to create projects, drag and dro ...

Permitted serverMiddleware hosts

I have developed a NUXT application and incorporated a serverMiddleware to handle REST endpoints and interact with my database. serverMiddleware: [ { path: "/api", handler: "~/api/index.js" }, ], I am now wondering how I can limit ac ...

What is the best way to trigger the opening of a Component upon an onPress event?

One challenge I am facing is implementing a button in my app's Screen that should open a self-made Modal component on the same screen. To achieve this, I have set up a visible state in the screen and created an onPress handler for the button to toggl ...

Tips for packaging an "express" application built on node.js with the help of Webpack

Seeking to package a node.js express application into a single file for distribution, I've turned to webpack. The bundling process seems to be successful, but upon attempting to run the app from the bundle, an error surfaces: Error: secure random n ...

My component reference seems to have gone missing in angular2

Trying to load my Angular 2 app, I encountered this error: https://i.stack.imgur.com/FmgZE.png Despite having all the necessary files in place. https://i.stack.imgur.com/kj9cP.png Any suggestions on how to resolve this issue? Here is a snippet from ap ...