2015-10-18 75 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