Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
Get response status code in a middleware

I am building an app in which I am trying to build my own logging system for each request.

For each request, I'd like to log the timestamp, the method used, the route, and finally the response code that has been sent to the client.

I have the following code for the moment :

// index.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
app.use(bodyParser.json());
app.use(cors());

app.use(require('./lib/logging'));

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

app.listen(3001);

// ./lib/logging.js
const moment = require('moment');
const chalk = require('chalk');
const log = console.log;

module.exports = (req, res, next) => {
  let now = `[${chalk.green(moment().format('HH:mm:ss'))}]`;
  let method = chalk.magenta(req.method);
  let route = chalk.blue(req.url);
  let code = chalk.yellow(res.statusCode); // Always 200
  log(`${now} ${method} request received on ${route} ${code}`);
  next();
}

Unfortunately, even if I do res.status(201).send('hello world') It will always catch a 200 status code... Is there a way to catch any response outgoing to the client and fetch its status code ?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Using the finish event from the response was indeed the good solution. The problem was in the finish event callback, I just couldn't use the arrow function because it wouldn't bind the this keyword, and this is were was stored the response data.

So the following code is working :

// ./lib/logging.js

const moment = require('moment');
const chalk = require('chalk');
const log = console.log;

module.exports = (req, res, next) => {
  let now = `[${chalk.green(moment().format('HH:mm:ss'))}]`;
  let method = chalk.magenta(req.method);
  let route = chalk.blue(req.url);
  res.on('finish', function() {
    let code = chalk.yellow(this.statusCode);
    log(`${now} ${method} request received on ${route} with code ${code}`);
  })

  next();
}

over 4 years ago · Santiago Trujillo Relatório

0

The Express response extends the Node.js http.ServerResponse, so you can listen for the 'finish' event:

Event: 'finish'

Emitted when the response has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been handed off to the operating system for transmission over the network. It does not imply that the client has received anything yet.

app.use((req, res, next) => {
  res.on('finish', () => {
    console.log(`Responded with status ${res.statusCode}`);
  });
  next();
});
over 4 years ago · Santiago Trujillo Relatório

0

Create middleware and Override send function

app.use(function (req, res) {
    var send = res.send;
    res.send = function (body) {
        // Do something
        send.call(this, body);
    };
});
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda