Meteor.call从服务器返回未定义到客户端

Meteor.call returning undefined from server to client

本文关键字:未定义 客户端 返回 服务器 call Meteor      更新时间:2023-09-26

我正在尝试在我的应用程序中对远程服务器进行 HTTP 调用

我有一个带有函数的包,该函数处理实际调用,然后将XML转换为JSON。

myPackage = {
baseUrl: "http://12.34.56.78:8080/api",
getBatchList: function() {
    var url = this.baseUrl + "/batchList.xml";
    HTTP.get(url, {auth: "user:pass"}, function(err, res) {
        if (!err) {
            console.log(res);
            xml2js.parseStringSync(res.content, function(error, result){
                if (!error) {
                    console.log(result); //the result is displayed
                    return result;
                };
            });
        };
    });
}
}

然后我在服务器上声明了一个 Meteor.method,这样我就可以从客户端调用该函数,因为 myPackage 仅在服务器上可用(它必须是,因为它对域外部进行 http 调用,我无法从客户端执行此操作)。

if (Meteor.isServer) {
Meteor.methods({
    getBatchList: function() {
        myPackage.getBatchList(function(error, result) {
            if (!error && result) {
                console.log(result); //nothing is logged to the console
                return result;
            };
        });
    }
})
}

但是,由于某种原因,结果似乎没有传递到 getBatchList 方法中,我怀疑是 我在回调的结构方式上有问题(我不知道);

最后在客户端上调用方法

if (Meteor.isClient) {
Template.hello.events({
    'click input' : function () {
        Meteor.call("getBatchList", function(error, result) {
            if (result && !error) {
                console.log(result);
            } else {
                console.log("nothing returned!!!");
            };
        });
    }
});
}

这也不会从服务器获得任何结果,没有错误或结果。

任何帮助将不胜感激。

谢谢。

问题是服务器上运行的代码是异步的,包括HTTP请求和函数本身。 我更改了代码如下

主要是不是返回 HTTP 调用的结果,而是我们现在返回调用本身。

if (Meteor.isServer) {
    Meteor.methods({
        getList: function() {
            var req = myPackage.getList();
            return req;
        }
    })
}; 

和 myPackage getList 函数

myPackage = {
    baseUrl: "http://12.34.56.78:8080/",
    getList: function() {
        var url = this.baseUrl + "/getList.xml";
        var req = HTTP.get(url, {auth: "user:pass"});
        if (req.statusCode === 200) {
            xml2js.parseStringSync(req.content, function(error, result){
                if (!error) {
                    req = result;
                };
            });
        };
        return req;
    }
}