如何在中间件调用中将参数传递给中间件?

时间:2019-07-24 23:12:24

标签: express mongoose

所以我试图在路由器的中间件调用中传递一个参数,然后在中间件中捕获该数据。

我一直收到以下错误:错误: Route.post()需要回调函数,但是得到了[object Promise]

// admin router

const express = require('express')
const Admin = require('../models/users/admin')
const auth_admin = require('../middleware/auth_admin')
const router = new express.Router()
const mongoose = require('mongoose')


router.post('/', auth_admin('text'), async (req, res) => {
   // code placeholder
})

module.exports = router



// middleware
const jwt = require('jsonwebtoken')
const Admin = require('../models/users/admin')

module.exports = function auth_admin(data) {
    return function async (req, res, next) {
        console.log(data)
        try {
            const token = req.header('Authorization').replace('Bearer ', '')
            const decoded = jwt.verify(token, 'f33~@%d6gf63geswg##@F3f')
            const admin = await Admin.findOne({ _id: decoded._id, 'tokens.token': token })
            
            if (!admin) {
                throw new Error()
            }
    
            req.token = token
            req.admin = admin
            next()
        } catch(err) {
            res.status(401).send({error: 'Authentication failed.'})
        }
    }
}

1 个答案:

答案 0 :(得分:0)

代替将附加参数add属性传递给req对象,然后在中间件函数中访问此属性。

例如:

// admin router
const express = require('express')
const Admin = require('../models/users/admin')
const auth_admin = require('../middleware/auth_admin')
const router = new express.Router()
const mongoose = require('mongoose')


router.post('/', async function async(req, res, next) {
    req.middlewareData =  'text';
    next()
}, auth_admin, async (req, res) => {
    // code placeholder
})

module.exports = router

// middleware auth_admin
const jwt = require('jsonwebtoken')
const Admin = require('../models/users/admin')

exports.auth_admin = function async(req, res, next) {
    console.log(req.middlewareData)
    try {
        const token = req.header('Authorization').replace('Bearer ', '')
        const decoded = jwt.verify(token, 'f33~@%d6gf63geswg##@F3f')
        const admin = await Admin.findOne({ _id: decoded._id, 'tokens.token': token })

        if (!admin) {
            throw new Error()
        }

        req.token = token
        req.admin = admin
        next()
    } catch (err) {
        res.status(401).send({ error: 'Authentication failed.' })
    }
}