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

105
Visualizações
Express not using middleware

I've encountered some strange behaviour, by using middleware on my express backend. I try to use the action middleware function before my invalidJsonDetection middleware function in index.js. If I destructure my action middleware function it is not working as expected, but if I assign the middleware function with middleware.general.action it is working as intended.

file 1: middleware.js

const middleware = {};

middleware.general = {
  action(req, res, next) {
    req.action = req.originalUrl; // simple task
    next();
  }
};
middleware.security = {
  invalidJsonDetection(err, req, res, next) {
    if (err instanceof SyntaxError && err.status === 400) {
      // with destructuring: req.action === undefined
      // without: req.action === req.originalUrl  
      res.json({ action: req.action, status: 'error' });
      return;
    }
    next();
  }
};

export default middleware;

file 2: index.js

import middleware from './middlewares/middleware.js';
const { action } = middleware.general;
const { invalidJsonDetection } = middleware.security;

const app = express();

// general middleware section
app.use(cors({ origin: 'http://localhost:8080', credentials: true }));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cookieParser());
app.use(action); // not working
// app.use(middleware.general.action); // working
app.use(invalidJsonDetection); // working as expected

app.post('/', (req, res, next) => { 
  res.json({ status: 'test' }); 
  return; 
});

app.listen(8081, () => {
  console.log(`Backend is listening on port 8081`);
  initDatabase();
});

Maybe someone could help me with this.

about 4 years ago · Juan Pablo Isaza
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