Reputation: 23
I am sure this is a ridiculously easy question but I think I have a mental block now about answering it.
I have installed node.js and express 4 and I can run static pages without any problem. What I want to do is to create a form to capture some data and then display the data I captured in the form in a results page. I am using Jade to handle the HTML part.
In the app.js file those were the only things I changed:
..
var routes = require('./routes/index');
var users = require('./routes/users');
// new routes
var helloworld = require('./routes/helloworld');
var sampleform = require('./routes/sampleform');
...
app.use('/', routes);
app.use('/users', users);
// new pages
app.get('/helloworld', helloworld);
app.get('/sampleform', sampleform);
I have a simple sampleform.jade file:
html
head
title Sample Form
body
h2 Sample Form
form(name='sampleform' action='/sampleform' method='post')
table(border='0')
tr
td Name
td
input(name='name' type='text' size='30')
tr
td Email
td
input(name='email' type='text' size='30')
tr
td
input(type='submit', name='submit', value='Submit')
I am able to load the form without problems using the following sampleform.js:
var express = require('express');
var router = express.Router();
/* GET sample form page. */
router.get('/sampleform', function(req, res) {
res.render('sampleform');
});
router.post('/showresults', function(req, res) {
res.render('showresults')
});
module.exports = router;
showresults.jade currently has only static content (I do not have a showresuls.js as this page is only called from sampleform.js):
html
head
title Show Results
body
h2 Show Results
What I need is that after the button submit is clicked in sampleform the new page called showresults is displayed (it will eventually have the data from sampleform but all I need right now is to have that page loaded). The code in sampleform.js above generates a 404 error and I know it does not work. What can I do instead? Am I missing something in the app.js code?
Thanks in advance for the help!
Upvotes: 2
Views: 1672
Reputation: 2762
From what I can see, you're submitting the form to a GET
route rather than a POST
route in your Jade file, here:
form(name='sampleform' action='/sampleform' method='post')
So rather than sending the form submission to that GET
request, you'll need to send it to a POST
. You have declared a POST
route here:
router.post('/showresults', function(req, res) {
So, you should only change the action
from the form in your Jade file to point to /showresults
because it's a POST
route rather than the GET /sampleform
. From there, you'll only need to call req.body
to retrieve the whole form you previously submitted.
Upvotes: 1