How to make a simple http request in Meteor from c

2020-04-01 08:34发布

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.

Client side:

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

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

Server Side

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; 
    } 
});

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.

1条回答
在下西门庆
2楼-- · 2020-04-01 08:45

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;
    }
  } 
});

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.

查看更多
登录 后发表回答