Reputation: 478
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
Upvotes: 0
Views: 1534
Reputation: 5542
I think there's another typo (dot), try:
app.use("/api/user", verifytoken.router);
Upvotes: 1
Reputation: 5412
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
Upvotes: 3