Kevin. J
Kevin. J

Reputation: 35

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!

Upvotes: 1

Views: 529

Answers (1)

BENARD Patrick
BENARD Patrick

Reputation: 30975

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;

Upvotes: 1

Related Questions