node.js - 如何简化在使用相同参数的路由内创建回调函数?
问题描述
我一直坚持在 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
});
};
解决方案
承诺应该避免回调地狱。所有流行的基于回调的库都有承诺的对应物,它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
.
推荐阅读
- c - 当我打印动态分配的数组时,它只打印最后一个值
- json - 根据 Flutter 中的选项组和选项计算产品变体
- assembly - 我想将 0x0000369c 数据存储到 0x000010fc 内存地址中。这个对吗?
- image-processing - 跨浏览器的图像解压一致性如何?
- node.js - 在这方面需要帮助:如何从 2021 年开始为 Dialogflow 上要在 Index.js 中使用的任何基本版本聊天机器人生成服务帐户密钥
- python - 命令引发异常:AttributeError: 'Guild' object has no attribute 'voice' 错误
- javascript - How to Restart fetch api request after aborting using AbortController
- node.js - Express、NodeMailer、React:发送带有表单值的电子邮件
- ios - 如何更改通过情节提要创建的 UIButton 的属性?
- java - 从androd(java)中的api获取最新数据