karthikeayan
karthikeayan

Reputation: 5030

is it possible to do two post routes in expressjs?

I created a Expressjs Application. It contains public, views, routes folders and app.js file.

I am having a post router for "/" path like this in app.js,

app.post('/', store.home_post_handler);

and the jade code,

#display
    #login        
        form(method='post')
            | Enter your name if you want to be a ninja
            div
                input(type='text', name='username')
                input(type='submit', value='Log In')

My question is, is it possible to have a two post methods in a single page?

Upvotes: 1

Views: 4275

Answers (1)

Plato
Plato

Reputation: 11072

If you want two forms on a client page, that do different things, the simplest way to differentiate the forms is to have them POST to different URL's by changing the action attribute of the form element.

If you require the forms to POST to the same URL, you should use @hexacyanide 's solution.

// app.js
app.get('/form', function(req, res){
  res.render('formTemplate');
});

app.post('/form1', function(req, res){
  console.log(req.body.foo);
});

app.post('/form2', function(req, res){
  console.log(req.body.bar);
});

// formTemplate.jade
!!!
  body
    form(action='form1', method='post')
      label(for='foo') Foo:
      input(type='text', name='foo', id='foo')
      input(type='submit', value='Submit Foo')
    form(action='form2', method='post')
      label(for='bar') Bar:
      input(type='text', name='bar', id='bar')
      input(type='submit', value='Submit Bar')

Upvotes: 2

Related Questions