0

Hi I am trying to export both a function (so that other routes may use this function to verify certs and also a the express router so that I can add it to my main class to mount the route on. This is because I believe the function and the route both serve the same sort of "functionality" and I want to encapsulate it in one file, so I want to export both the function and the router to use! Here is the following code of which I get an error... Note I WANT to do verifytoken.router to refer to the router and then verifytoken.verify to refer to the function in other files

/routes/verifytoken.js file

const router = require('express').Router();
const jwt = require('jsonwebtoken');

function verify (req, res, next) {
    const token = req.header("auth-token");
    if (!token) return res.status(401).send("Access Denied");

    try {
        const verified = jwt.verify(token, process.env.TOKEN_SECRET);
        req.user = verified;
        next();
    } catch (error) {
        res.status(400).send("Invalid Token")
    }
}

router.get("/tester", (req, res) => {
    res.status(200).send("validation please work bro"); 
});

module.exports = {
    verify:verify,
    router:router
}

my main index.js file

const express = require('express');

//import routes
const verifytoken = require('./routes/verifytoken')

const app = express(); 

//route middlewares
app.use("/api/user". verifytoken.router);

app.listen(3000 , () => console.log('Server Running...'))

The stack trace is :

app.use("/api/user". verifytoken.router);
                                 ^

TypeError: Cannot read property 'router' of undefined
nuxer
  • 438
  • 1
  • 6
  • 20

2 Answers2

3

1) Another typo:

app.use("/api/user". verifytoken.router);

Should be: (note dot . instead of comma ,)

app.use("/api/user", verifytoken.router);

2) You're using the wrong filename in the imported module:

const verifytoken = require('./routes/verifytoken');

Should be:

const verifytoken = require('./routes/verify');

The required file is named verify.js not verifytoken.js

Kostas Minaidis
  • 4,681
  • 3
  • 17
  • 25
  • sorry I misspelt the filename i updated it the filenames are correct. Its still not working – nuxer Feb 15 '20 at 20:26
  • no its the same error I just had a typo when making this post, try running this locally youll get the same error – nuxer Feb 15 '20 at 20:32
  • OH MY GOD THIS WAS THE ERROR THANK YOU GUYS SO MUCH!!!! the DOT – nuxer Feb 15 '20 at 20:40
1

I think there's another typo (dot), try:

app.use("/api/user", verifytoken.router);
Tamas Szoke
  • 5,426
  • 4
  • 24
  • 39