Meteor - 如何从URL参数获取服务器数据?

时间:2016-02-23 20:00:49

标签: meteor client-server single-page-application iron-router

我正在尝试根据MeteorJS中路由上的URL参数返回不同的数据。

从nodejs背景,我会这样做:

testPage = function (req, res, next) {
    //Got parameter query from url
    console.log('Getting at /testPage/:query '+req.params.query);

    //do something with that parameter, say make an HTTP call or query database
    var newThing = req.params.query+"hi";

    // render the page
    var data = {
        foo: newThing
    };
    res.render('testPage', data);
};

Meteor不支持服务器端渲染,所以就这样了。我仍然围绕着Meteor的单页客户端渲染;我应该如何在流星中解决这个问题?

我的第一次尝试(使用IronRouter):

Router.route('/testPage/:query', function () {
    console.log("Got param at /testPage/:query "+this.params.query);
    if(Meteor.isServer){
        console.log("This code may never be called?");
        //Otherwise, make an HTTP call 
        //  and then somehow pass the data back to the client...
    }
    this.render("query");
});

这是我能用反应变量做的事吗?或者也许从客户端进行AJAX调用以分离服务器端点?

3 个答案:

答案 0 :(得分:1)

使用iron-router的规范模式是使用route参数订阅数据:

this.params.bar

在此示例中,Meteor.subscribe是路由的唯一参数。它作为参数传递给waitOn。服务器可以使用该参数来决定要发布回客户端的内容。 {{1}}保证在模板渲染时数据在客户端上可用。

答案 1 :(得分:0)

您可以将.render方法上的数据作为第二个参数传递

Router.route('/testPage/:query', function () {
    console.log("Got param at /testPage/:query "+this.params.query);
    if(Meteor.isServer){
        console.log("This code may never be called?");
        //Otherwise, make an HTTP call 
        //  and then somehow pass the data back to the client...
    }
    this.render("query", {data: queryResult });
});

答案 2 :(得分:0)

从我的观点来看,定义服务器端JSON API端点的最简单的基本方法,没有任何其他附加功能。基于此连接路由。我建议您只需从该处理程序函数中引发Error或Meteor.Error。

此后,您可以附加错误处理中间件,该中间件可以将这些错误转换为JSON并发送响应。

Resource link

相关问题