简体   繁体   中英

Meteor: Exception in delivering result of invoking method

Similar issues have been posted, but none quite match what I've run into. I'm doing a simple POST to an internal server to get back product data. The call is successful and I see the JSON data correctly logging to my terminal when I do a console.log on the server side. The issue arises on the client side, when in the callback, the result and error both are undefined.

Server:

Meteor.methods({
    ProductSearch: function(searchTerm) {
        var method = 'POST';
        var url = 'server';
        var options = {
            headers:{"content-type":"application/json"},
            data: { 
                query:"trees"
            }
        };
        return HTTP.call(method, url, options, function (error, result) {
            if (error) {
                console.log("ERROR: ", result.statusCode, result.content);
            } else {
                var txt = JSON.parse(result.content);
                console.log("SUCCESS: Found "+txt.totalResults+" products");
            } 
        });
    }
});

Client:

Meteor.call('ProductSearch', searchTerm, function (error, result) {
    if (error) {
        console.log("error occured on receiving data on server. ", error );
    } else {
        var respJson = JSON.parse(result.content);
        Session.set("productSearchResults", respJson);
    }
});

When I log the values of error , and result on callback, they are both undefined, and I get the following error: 出现

In your server-side method, you're not correctly returning the result of the HTTP.call , since you're using the asynchronous version, HTTP.call will return undefined and the result will only be accessible in the callback.

Use the synchronous version of HTTP.call instead and you'll be fine.

try{
  var result = HTTP.call(method, url, options);
  return JSON.parse(result.content);
}
catch(exception){
  console.log(exception);
}

See the corresponding docs for HTTP.call for additional information.

asyncCallback Function

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

https://docs.meteor.com/#/full/http_call

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM