How to make a simple http request in Meteor from client to server

ぃ、小莉子 提交于 2019-12-19 12:51:06

问题


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:


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.



来源:https://stackoverflow.com/questions/34093534/how-to-make-a-simple-http-request-in-meteor-from-client-to-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!