Search code examples
javascriptpostmeteorurl-routingiron-router

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


I'm writing an app with Meteor that needs to take data from POST requests and also render a success page on the same route. This is my current code for the /submit route:

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

When I run this code, the data is inserted into the Records database, but it never renders the success template. When I go to the /submit route, it just loads forever and never actually shows anything on the page. When I get rid of the {where: 'server'} it will render the template but not add the data to the database.

How do I get both the data to be added and the template to render?


Solution

  • The problem is that a to POST data to a route it must be run on the server and you cannot render a client-side template from a server route. One way to fix this is to use a 302 redirect to get back into the client side, like this (code is 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'
    

    The server route receives the POSTed data and acts on it before redirecting to the client route. The name of the client route is used to identify the template to be rendered.