如何在Meteor中从客户端到服务器进行简单的http请求 [英] How to make a simple http request in Meteor from client to server

查看:581
本文介绍了如何在Meteor中从客户端到服务器进行简单的http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次使用Meteor,我正在尝试在方法中进行简单的http调用,因此我可以从客户端调用此方法。

I'm using Meteor for first time and i'm trying to have a simple http call within a method so i can call this method from the client.

问题是这个异步调用它会继续运行,即使我把它放在一个包装器中。

The problem is that this async call it's keep running even if i put it within a wrapper.

客户端:

Meteor.call('getToken', function(error, results) {
      console.log('entered');

      if(error) {
        console.log(error);
      } else {
        console.log(results);
      }
    });

服务器端

Meteor.methods({
    getToken: function(){

        // App url
        var appUrl = 'myAppUrl';

        // Key credentials
        var apiKey = 'mykey';
        var apiSecret = 'mySecret';

        function asyncCall(){
            Meteor.http.call(
                'POST',
                appUrl,
                {
                    data: { 
                        key: apiKey, 
                        secret: apiSecret
                    }
                }, function (err, res) {
                    if(err){
                      return err;
                    } else {
                      return res;
                    }
                }
            );
        }

        var syncCall = Meteor.wrapAsync(asyncCall);

        // now you can return the result to client.
        return syncCall; 
    } 
});

我总是得到一个未定义的回报。
如果我在http.post调用中记录响应,我正在确定正确的响应。
如果我尝试记录syncCall,我什么也得不到。

I'm always getting an undefined return. If i log the response within the http.post call i'm geting the correct response. If i try to log the syncCall i get nothing.

我非常感谢你的任何帮助。

I would very appreciate any help on this.

推荐答案

您应该使用 HTTP的同步版本。在这种情况下发布。尝试这样的事情:

You should use the synchronous version of HTTP.post in this case. Give something like this a try:

Meteor.methods({
  getToken: function() {
    var appUrl = 'myAppUrl';
    var data = {apiKey: 'mykey', apiSecret: 'mySecret'};
    try {
      var result = HTTP.post(appUrl, {data: data});
      return result;
    } catch (err) {
      return err;
    }
  } 
});

而不是返回错误我是建议确定抛出了什么类型的错误,然后只需抛出新的Meteor.Error(...),这样客户端就可以将错误视为其第一个回调参数。

Instead of returning the err I'd recommend determining what kind of error was thrown and then just throw new Meteor.Error(...) so the client can see the error as its first callback argument.

这篇关于如何在Meteor中从客户端到服务器进行简单的http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆