能否为Express的app.use()传递参数?
如何给Express中间件传递自定义参数(硬编码Token)
问题背景
我有一段可正常运行的Express代码:
import express from 'express'; const port = 8080; const app = express(); function auth(req, res, next) { const token = req.headers['authorization']?.split(' ')[1]; if (token == null) res.sendStatus(401); token === 'example=' ? next() : res.sendStatus(403); } app.use(auth); app.listen(port, () => { console.log(`Example app listening on port ${port}`); });
我想把硬编码的example=改成可传递的参数,于是尝试修改成如下形式:
function auth(req, res, next, hardcodedToken) { const token = req.headers['authorization']?.split(' ')[1]; if (token == null) res.sendStatus(401); token === hardcodedToken ? next() : res.sendStatus(403); } app.use(auth((hardcodedToken = 'example=')));
但运行时报错:
ReferenceError: hardcodedToken is not defined
想问:有没有办法将hardcodedToken变量传递给auth()函数?若有需要,我可以切换到TypeScript。
解决方案
Express中间件的固定签名是(req, res, next),无法直接添加额外参数。要传递自定义参数,你可以通过高阶函数或闭包实现:
方法1:高阶函数(推荐)
让auth作为高阶函数,先接收自定义token参数,再返回符合Express要求的中间件函数:
import express from 'express'; const port = 8080; const app = express(); // 高阶函数:接收token参数,返回中间件 function auth(hardcodedToken) { return (req, res, next) => { const token = req.headers['authorization']?.split(' ')[1]; if (token == null) return res.sendStatus(401); token === hardcodedToken ? next() : res.sendStatus(403); }; } // 使用时传入指定token app.use(auth('example=')); app.listen(port, () => { console.log(`Example app listening on port ${port}`); });
方法2:闭包捕获外部变量
如果不想修改函数结构,可通过闭包让中间件直接访问外部定义的token变量:
import express from 'express'; const port = 8080; const app = express(); const hardcodedToken = 'example='; // 外部定义的token function auth(req, res, next) { const token = req.headers['authorization']?.split(' ')[1]; if (token == null) return res.sendStatus(401); token === hardcodedToken ? next() : res.sendStatus(403); } app.use(auth); app.listen(port, () => { console.log(`Example app listening on port ${port}`); });
TypeScript版本
若切换到TypeScript,可添加类型定义让代码更严谨:
import express, { Request, Response, NextFunction } from 'express'; const port = 8080; const app = express(); function auth(hardcodedToken: string) { return (req: Request, res: Response, next: NextFunction) => { const token = req.headers['authorization']?.split(' ')[1]; if (token == null) return res.sendStatus(401); token === hardcodedToken ? next() : res.sendStatus(403); }; } app.use(auth('example=')); app.listen(port, () => { console.log(`Example app listening on port ${port}`); });
内容的提问来源于stack exchange,提问作者Sandra Schlichting
相关产品推荐
相关产品推荐

