gpt4 book ai didi

javascript - Meteor 方法向客户端返回 undefined (异步)

转载 作者:太空宇宙 更新时间:2023-11-04 00:42:43 24 4
gpt4 key购买 nike

我一直致力于将 Google Recaptcha 集成到 Meteor 和 AngularJS Web 应用程序中。一切都很顺利,直到我必须验证验证码响应 - 由于某些奇怪的原因,我无法获得从后端到前端的异步响应。

我尝试了很多不同的变体,并且阅读了 SO 和互联网上的很多帖子,但没有运气 - 所以我选择发布我自己的问题。

<小时/>

这就是我正在做的事情:

客户:

Meteor.call('recaptcha.methods.validateRecaptcha', { 'response' : this.recaptcha.getResponse(this.id) }, function(error, result) {
// error and result are both undefined
console.log('Do something with the ' + error + ' or ' + result + '.');
}

因此,我调用 Meteor 方法并传入一个回调,该回调在该方法完成时运行。然而,errorresult参数均未定义。

服务器:

run: function(data) {
if (this.isSimulation) {
/*
* Client-side simulations won't have access to any of the
* Meteor.settings.private variables, so we should just stop here.
*/
return;
}

return Meteor.wrapAsync(HTTP.post)(_someUrl, _someOptions);
}

最后一行是我在几个 Meteor 指南中找到的同步/异步结构的缩短版本(我也尝试过这个版本),即:

var syncFunc = Meteor.wrapAsync(HTTP.post);
var result = syncFunc(Meteor.settings.private.grecaptcha.verifyUrl, _options);
return result;

我还尝试过使用 Futures 的版本:

var Future = Npm.require( 'fibers/future' );
var future = new Future();
var callback = future.resolver();
HTTP.post(Meteor.settings.private.grecaptcha.verifyUrl, _options, callback);

return future.wait();
<小时/>

现在,我的目的是使用 Meteor.call()要从客户端调用此方法,客户端 stub 会运行(为了防止模拟错误,因为我们在真正的非 SO 服务器端代码中使用私有(private) Meteor.settings 变量)并立即返回(这种情况会发生),服务器会在将结果返回给客户端之前调用 Google 的 Recaptcha API(这种情况会发生,服务器会收到响应)(这种情况不会发生 - 会发生回调,但没有错误/成功数据)。

我的想法是发生了以下两件事之一:

  1. 我只是做错了什么,并且没有正确地将数据发送回客户端。
  2. 同步客户端 stub (立即返回)告诉客户端服务器响应并不重要,因此它永远不会等待正确的异步响应。

任何 Meteor 专家能否在这里发表意见并让我知道发生了什么以及如何让异步请求在 Meteor 应用程序中正常运行?

谢谢!

最佳答案

来自documentation对于 HTTP.call,它是 HTTP.post 的通用版本,它说

Optional callback. If passed, the method runs asynchronously, instead of synchronously, and calls asyncCallback. On the client, this callback is required.

因此,在服务器上,您可以像这样异步运行它

run: function(data) {
if (this.isSimulation) {
/*
* Client-side simulations won't have access to any of the
* Meteor.settings.private variables, so we should just stop here.
*/
return;
}

// No need to pass callback on server.
// Since this part is not executed on client, you can do this
// Or you can use Meteor.isClient to run it asynchronously when the call is from client.
return HTTP.post(Meteor.settings.private.grecaptcha.verifyUrl, _options);
}

关于javascript - Meteor 方法向客户端返回 undefined (异步),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36024764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com