Express.js 在中间件中获取 header

Express.js get header in mddleware

我为添加到 header 的 auth api 密钥创建了中间件。

const loger = require("easy-loger");

require('dotenv').config();
function authMiddleware(req, res, next){
    const appApiKey = process.env.API_KEY;
    let requestApiKey = req.headers.apikey;

    if(requestApiKey === "undefined"){
        loger.createLog('Try to authorize without api key from : '+ req.headers.host, 'info');
        res.status(401);
        res.json({
            code: 403,
            message: 'You need to authorize in this route'
        });
    }

    if(appApiKey === requestApiKey){
        next();
    }else {
        loger.createLog('Try to authorize user without rights with api key: '+ requestApiKey, 'info');
        res.status(403);
        res.json({
            code: 403,
            message: 'You have not permission for this route'
        });
    }
}

如果我将其作为函数添加到路由中,一切正常,但如果我尝试将其用作模块,则会出现如下错误:

 let requestApiKey = req.headers.apikey;
                        ^

TypeError: Cannot read property 'headers' of undefined

如何在导出模块 mddleware 中获取 heders?

// in authMiddleware file you need to export the middleware
module.exports = { authMiddleware }

// in the file you use it, you need to :
const { authMiddleware } = require('../modules/auth/authMiddleware');
router.use(authMiddleware );