【问题标题】:Meteor: Exception in delivering result of invoking methodMeteor:传递调用方法的结果时出现异常
【发布时间】:2015-09-23 19:13:36
【问题描述】:

已经发布了类似的问题,但没有一个完全符合我遇到的问题。我正在对内部服务器进行简单的 POST 以获取产品数据。调用成功,当我在服务器端执行 console.log 时,我看到 JSON 数据正确记录到我的终端。问题出现在客户端,在回调中,结果和错误都未定义。

服务器:

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

客户:

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

当我在回调中记录 errorresult 的值时,它们都是未定义的,并且我收到以下错误:在传递结果时出现异常调用“ProductSearch”:TypeError:无法读取未定义的属性“内容”

【问题讨论】:

    标签: javascript meteor


    【解决方案1】:

    在您的服务器端方法中,您没有正确返回 HTTP.call 的结果,因为您使用的是异步版本,HTTP.call 将返回 undefined 并且结果只能在回调。

    改用HTTP.call 的同步版本就可以了。

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

    有关更多信息,请参阅HTTP.call 的相应文档。

    asyncCallback函数

    可选回调。如果通过,则方法运行 异步,而不是同步,并调用 asyncCallback。上 客户端,这个回调是必需的。

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

    【讨论】:

    • 我无法告诉你我阅读了多少次HTTP.call 的规范,完全错过了回调是可选的!非常感谢。
    猜你喜欢
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多