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

119
Visualizações
Node.js - Functions from another file as parameter in a route

I'm trying to make my program a bit more modular because it's quite a mess now. But for every attempt at refactoring my code I always get a bunch of errors and a program that doesn't work.

What I want to do is create multiple files that have their own workload and if I need something of it in another file, I can basically "borrow" that function.

Example from my existing code :

Index.js

//Routers 
const getPostsRouter = require('./routes/getPosts');
app.use('/getPosts', getPostsRouter);

///////////////////////////////////////////////////////////////////////////////////////////////

const authenticateToken = (req, res, next) => {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1]
    if (token == null) return res.sendStatus(401);

    jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
        if (err) return res.sendStatus(403);
        req.user = user
        next()
    })
}

module.exports = authenticateToken;

Then in my getPosts.js file I want to be able to do something like

const express = require('express');
const router = express.Router();
const db = require('../databaseConnection');
const {authenticateToken} = require('../index')

router.get('/', authenticateToken, async (req, res) => {
        await db.query('SELECT * FROM posts', 
        (err, result) => {
            if (err) {
                res.send({errorMessage: err});
            }
            res.send(result);
        });
    }
}); 

module.exports = router;

But I always get this error when I try this : "Error: Route.get() requires a callback function but got a [object Undefined]" which points to the line "const getPostsRouter = require('./routes/getPosts');" in index.js

EDIT: The problem lied in circular dependencies! All I needed to do was erase one side of the dependency and now everything works as intended!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Remove the brackets, because you're always exporting authenticateToken by defualt...

const express = require('express');
const router = express.Router();
const db = require('../databaseConnection');
const authenticateToken = require('../index'); // <---- HERE

router.get('/', authenticateToken, async (req, res) => {
        await db.query('SELECT * FROM posts', 
        (err, result) => {
            if (err) {
                res.send({errorMessage: err});
            }
            res.send(result);
        });
    }
}); 

module.exports = router;
about 4 years ago · Juan Pablo Isaza 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