Express按查询参数调用路由处理函数报错:res.redirect不是函数
问题
对接外部API的OAuth2.0流程初始阶段,外部服务会携带hmac等查询参数将用户导向应用根路径(此阶段早于用户授权后的回调)。需求是:当请求无hmac参数时返回静态站点,存在该参数时调用单独的处理函数。
原本将验证代码直接写在app.get('/')的else分支可正常运行,但拆分到handleHmac函数后,出现「TypeError: res.redirect is not a function」错误,相关代码如下:
const morgan = require('morgan'); const app = express(); app.use(morgan('dev')); app.get('/', (req, res, next) => { if (!req.query.hmac) { console.log('No special params. Serving static.'); next(); } else { console.log('handling hmac parameter'); handleHmac(res, req); } }) app.use(express.static('public')); const handleHmac = (req, res) => { //validate hmac and ultimatley redirect to external auth site console.log('handleHmac function called') //successfully prints in test res.redirect('/mockexternal.html') //TypeError: res.redirect is not a function } app.listen(3000, () => { console.log('Listening on Port 3000') })
解决方法
错误原因
调用handleHmac时的参数顺序和函数定义的顺序完全相反:
handleHmac函数定义的参数顺序是(req, res)- 实际调用时传的是
handleHmac(res, req)
这导致函数内部的req变量实际是响应对象(res),res变量实际是请求对象(req),而请求对象没有redirect方法,因此触发错误。
修正方案
将调用handleHmac时的参数顺序调整为(req, res),符合Express中间件的常规参数顺序:
const morgan = require('morgan'); const app = express(); app.use(morgan('dev')); app.get('/', (req, res, next) => { if (!req.query.hmac) { console.log('No special params. Serving static.'); next(); } else { console.log('handling hmac parameter'); handleHmac(req, res); // 修正参数顺序 } }) app.use(express.static('public')); const handleHmac = (req, res) => { //validate hmac and ultimatley redirect to external auth site console.log('handleHmac function called') res.redirect('/mockexternal.html') // 现在res是正确的响应对象,可正常调用redirect } app.listen(3000, () => { console.log('Listening on Port 3000') })
内容的提问来源于stack exchange,提问作者Gordon
相关产品推荐
相关产品推荐

