I have an express app like so:
// index.js
const express = require('express');
const app = express();
const userRoutes = require('./routes/userRoutes');
app.use('/user', userRoutes);
const verifyToken = (req, res, next) => {
// validate req.cookies.token
next();
}
And I'm using an express router module like this:
// routes/userRoutes.js
const express = require('express');
const router = express.Router();
router.get('/:userid/data', verifyToken, async (req, res) => {
const data = await db.query()
res.json(data)
});
Obviously this doesn't work because verifyToken
is not accesible within the module. How can I use the same verifyToken
middleware function throughout different express modules?
Move verifyToken
to a different file and export
it from there.
Then you can import
it in other places.
One thing that you can do, that works well is to group all your authed routes under a common path and use router.use
to make sure that you apply the verifyToken
middleware on all of them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.