2

我試圖根據MeteorJS中的路由上的URL參數返回不同的數據。流星 - 我如何從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的單頁客戶端渲染進行包裝;我應該如何在流星中做這件事?

我第一次嘗試(使用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調用以分離服務器端點?

+0

我建議在路由更改時在客戶端上獲取查詢參數。然後用新參數調用服務器方法。 Router.current()是被動的,所以你可以檢查自動運行中的參數,並把你的方法調用到裏面。如果我有時間,我會嘗試製作一個Meteorpad來演示。 – looshi

回答

1

這種情況的典型圖案與鐵路由器是訂閱使用路線參數(一個或多個)數據:

Router.route('/foo/:bar',{ // Route takes a single parameter 
    name: 'foo', 
    waitOn: function(){ 
    return Meteor.subscribe('fooPublication', this.params.bar); 
    } 
}); 

在這個例子中是this.params.bar路由的唯一參數。它作爲參數傳遞給Meteor.subscribe。服務器可以使用該參數來決定發佈回客戶端的內容。 waitOn保證模板呈現時客戶端上的數據將可用。

+1

對於任何其他不瞭解訂閱/發佈的人,我將Meteor.publish放在我的基本服務器代碼中,並在調用此訂閱函數時調用!正是我在找什麼 – hubatish