Languages

Node.js / Express.js - middleware executes twice

0 points
Asked by:
Hayley-Mooney
377

Why is my middleware executing twice when I send request to the '/' route?

My code:

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

app.use((req, res, next) => {
  console.log('Before response');
  next();
});

app.get('/', (req, res, next) => {
  res.send('Response');
  next();
});

app.use('/', (req, res) => {
  console.log('After response');
});

app.listen(3000);

Result:

Before response
After response
Before response
After response
1 answer
0 points
Answered by:
Hayley-Mooney
377

Defining app.use() functions before the app.get() request fixes this problem.

Your code should look like this:

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

app.use((req, res, next) => {
  console.log('Before response');
  next();
});

app.use('/', (req, res) => {
  console.log('After response');
});

// GET request moved here
app.get('/', (req, res, next) => {
  res.send('Response');
  next();
});

app.listen(3000);

Now the console result is:

Before response
After response
0 comments Add comment
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join