2015-10-18 73 views
0

我正在用Meteor編寫一個應用程序,需要從POST請求中獲取數據,並在同一路線上呈現成功頁面。這是我當前的代碼/提交路線:鐵:路由器+流星 - 不能同時添加POST數據到數據庫並渲染路由

Router.route('/submit', function() { 
    Records.insert({ 
     testValue: 'The Value', 
     importantVal: this.request.body.email, 
     createdAt: new Date() 
    }); 
    this.render('success'); 
}, {where: 'server'}); 

當我運行此代碼,將數據插入到數據庫中的記錄,但它從來沒有渲染的成功模板。當我進入/提交路線時,它只會永久加載,並且從不實際顯示頁面上的任何內容。當我擺脫{其中:'服務器'}它將呈現模板,但不會將數據添加到數據庫。

我該如何獲得要添加的數據和要呈現的模板?

回答

2

外的問題是,POST數據到它必須在服務器上運行的路線,你無法呈現從服務器路由客戶端模板。解決這個問題的方法之一是使用302重定向到重新進入客戶端,像這樣的(代碼是CoffeeScript的):

Router.route '/submit', where: 'server' 
    .post -> 
     Records.insert 
      testValue: 'The Value' 
      importantVal: @request.body.email 
      createdAt: new Date() 
     @response.writeHead 302, 'Location': '/success' 
     @response.end() 

Router.route '/success', name:'success' 

server路由重定向到client之前接收發布數據,並作用於它路線。 client路徑的名稱用於標識要呈現的模板。

+0

運行此代碼會導致錯誤,因爲它的結構方式(不包含括號中的路徑...)。嘗試重構此代碼以通過將渲染更改爲this.response.writeHead(302,{'Location':'/ success'})來處理當前代碼。 this.response.end();並添加新的路線/成功似乎並沒有解決我的問題。 – meecoder

+0

實際上,這似乎是由於我忘記了this.response.end()結尾處的括號而引起的。謝謝您的幫助! – meecoder

+1

對不起缺乏括號等,我忘了提及代碼是在咖啡腳本,我已經解決了這個問題的答案。 – biofractal

0

試試這個isClientisServer

Router.route('/submit', {  
    template: 'success', 
    onBeforeAction: function(){ 
     Records.insert({ 
     testValue: 'The Value', 
     importantVal: $('[name=email]').val(),//email from input field with name="email" 
     createdAt: new Date() 
    }); 
    } 
}); 
+0

這給了我同樣的錯誤,我添加{其中:'服務器'}我的路線:在異步函數回調異常:TypeError:無法讀取未定義的屬性'電子郵件' – meecoder

+0

'request'沒有'body'屬性..如果電子郵件是由用戶輸入的,你可以首先得到電子郵件'importantVal:$('[name = email]')。val()' – danleyb2

+0

我從Meteor服務器的單獨服務器並需要通過POST請求獲取它。我無法在客戶端上運行jQuery代碼,因爲表單位於單獨的域中。 – meecoder