I just tried the following express 4 app, that simply sends a selected fruit from client to server and server suppose to respond back the name of the fruit. I got this example from here. The original example uses the template engine nunjucks by Mozilla. However, I adopted it to express-handlebars.
// app.js
var express = require('express'),
app = express(),
engines = require('consolidate'),
bodyParser = require('body-parser'),
exphbs = require('express-handlebars');
// view engine setup
app.engine('hbs', exphbs({extname: 'hbs', defaultLayout: 'main', layoutDir: __dirname + '/views/layouts/'}));
app.set('views', __dirname+'/views');
app.set('view engine', 'hbs');
//app.engine('html', engines.nunjucks);
//app.set('view engine', 'html');
//app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({ extended: true }));
// Handler for internal server errors
function errorHandler(err, req, res, next) {
console.error(err.message);
console.error(err.stack);
res.status(500).render('error_template', { error: err });
}
app.use(errorHandler);
app.post('/favorite_fruit', function(req, res, next) {
// res.redirect('/favorite_fruit');
var favorite = req.body.fruit;
console.log(favorite);
if (typeof favorite == 'undefined') {
next('Please choose a fruit!');
}
else {
res.send("Your favorite fruit is " + favorite);
}
});
app.get('/', function(req, res, next) {
res.render('fruitPicker', { 'fruits' : [ 'apple', 'orange', 'banana', 'peach' ] });
});
var server = app.listen(3000, function() {
var port = server.address().port;
console.log('Express server listening on port %s.', port);
});
Here is my
<!--views/fruitPicker.hbs-->
<form action='/favorite_fruit' mehtod='POST'>
<p>What is your favorite fruit?</p>
{{#each fruits}}
<p>
<input type="radio" name="fruit" value="{{this}}"/>{{this}}
</p>
{{/each}}
<input type="submit" value="Submit"/>
</form>
My views/layouts/main.hbs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{title}}</title>
</head>
<body>
{{{body}}}
</body>
</html>
When I go to localhost:3000, it shows the form, but when I click on the submit button, it takes me to another page that says:
Cannot GET /favorite_fruit?fruit=orange
I have seen videos they fix this using a click handler on the submit button using ajax. But in the example with nunjucks, there is not need to attach a click handler on the form's submit button. I don's see why I need this with if I use express-handlebars. Is there an issue with my code. Please help. Thank you very much.