首页 > 解决方案 > 如何简化在使用相同参数的路由内创建回调函数?

问题描述

我一直坚持在 node/express 中创建重复使用相同参数的包装回调函数的最佳方法。

问题是验证需要与回调相同的参数。有没有办法简化这个?我在堆栈和谷歌上寻找过这个,但找不到答案。我不想在实际调用中写 req, res, next 两次。我知道第一个 req, res, next 被汇集到回调中,但是这样写仍然感觉很奇怪。感觉肯定有更好的方法,但我只是不知道那是什么。

情况如下:

function verifyCaptcha(req, res, next, callback) {

    let captchaResponse = req.body.captchaResponse;

    let captchaSecret = "it's a secret";

    let captchaURL = "https://www.google.com/recaptcha/api/siteverify?"
    + "secret=" + encodeURIComponent(captchaSecret) + "&"
    + "response=" + encodeURIComponent(captchaResponse) + "&"
    + "remoteip" + encodeURIComponent(req.connection.remoteAddress);

    // request is ASYNC, that's why I need the callback
    request(captchaURL, function(error, response, body) {
        callback(req, res, next);
        return;
    });
};


router.post('/login', function(req, res, next) {

    // example call INSIDE a route (here's the problem b/c params are repeated in the call
    verifyCaptcha(req, res, next, function(req, res, next){
        // do stuff
    });

};

标签: node.jsexpressasynchronous

解决方案


承诺应该避免回调地狱。所有流行的基于回调的库都有承诺的对应物,它request-promise用于request. 这可以用类似同步的方式编写async..await

const request = require('request-promise');

async function verifyCaptcha(req, res) {
    let captchaResponse = req.body.captchaResponse;

    let captchaSecret = "it's a secret";

    let captchaURL = "https://www.google.com/recaptcha/api/siteverify?"
    + "secret=" + encodeURIComponent(captchaSecret) + "&"
    + "response=" + encodeURIComponent(captchaResponse) + "&"
    + "remoteip" + encodeURIComponent(req.connection.remoteAddress);

    const result = await request(captchaURL);
    ...
};


router.post('/login', async function(req, res, next) {
    try {
        await verifyCaptcha(req, res);
    } catch (err) {
        next(err);
    }
};

正如在这个问题中解释的那样,Express 本身不支持承诺,所有拒绝都应该由开发人员处理,async中间件/处理程序函数体应该用try..catch.


推荐阅读