铁:路由器+流星-不能同时添加POST数据到数据库和渲染路由

Iron:Router + Meteor - Can't both add POST data to database and render route

本文关键字:数据 POST 数据库 路由 添加 路由器 流星 不能      更新时间:2023-09-26

我正在用Meteor编写一个应用程序,需要从POST请求中获取数据,并在同一路由上呈现成功页面。这是我当前的/submit路由代码:

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

当我运行这段代码时,数据被插入到Records数据库中,但它从不呈现成功模板。当我转到/submit路由时,它会永远加载,不会在页面上显示任何内容。当我摆脱{where: 'server'},它将呈现模板,但不添加数据到数据库。

如何获得要添加的数据和要呈现的模板?

问题是,要将数据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路由接收到post数据,在重定向到client路由之前对其进行处理。client路由名称用于标识待渲染的模板

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()
    });
   }
});