Reputation: 5747
I've read several other questions about how to configure express to listen on POST requests but I continually get empty JSON or undefined when I try to print out simple POST queries that I send to the server.
I have this set up:
//routes
require('./routes/signup.js')(app);
// Configuration
app.configure(function(){
app.use(connect.bodyParser());
app.use(express.methodOverride());
app.register(".html", hulk);
app.set('views', __dirname + '/views');
app.set('view options', {layout: false});
app.set('view engine', 'hulk');
app.use(express.static(__dirname + '/public'));
app.use(app.router);
});
then routes/signup.js
looks like this:
var common_functions = require('../common_functions.js');
var views = require('../views/view_functions.js');
var globals = require('../globals.js');
var mongoose = require('mongoose');
//declare classes
var User = mongoose.model('User');
module.exports = function(app){
/**
* SignUp GET
*/
app.get('/signup', function(req, res){
res.render('signup/signup.html');
});
/**
* SignUp POST
*/
app.post('/signup', function(req, res){
console.log(JSON.stringify(req.body));
console.log(req.body);
res.send(JSON.stringify(req.body));
});
}
the template looks like this:
{{> header.html }}
{{> navigation.html }}
{{> body.html }}
<form action="/signup" method="post">
<input name="email"/>
<input type="submit"/>
</form>
{{> footer.html }}
There is nothing of particular interest in any of the partials.
The two console.log
's print out undefined while the res.send()
simply return the same html as before. What am I doing wrong here?
Upvotes: 0
Views: 3722
Reputation: 4847
Express auto-mounts the router middleware, if not already mounted, on the first call to any of the router's verb functions. So, by loading in routes above the config block, the router middleware is the first middleware in the stack (above the bodyParser). Moving the route file loading below the configure block will fix this issue.
From the configuration section of the Express.js docs:
Note the use of app.router, which can (optionally) be used to mount the application routes, otherwise the first call to app.get(), app.post(), etc will mount the routes.
http://expressjs.com/guide.html#configuration
Upvotes: 1