Express Server - Cannot POST / [duplicate]
There are actually a couple of problems, but the main one is that you don't have a body parser - the module that converts a node stream in the POST to a req.body
. I am currently only familiar with bodyParser
, and you should probably research that a bit. Although it is shown in Express 4.x documentation, you get a deprecation message when you run the server.
The other problem is the issue of comments.push
. That should be comments.comments.push
. The following works:
router.js:
var fs = require('fs');var ejs = require('ejs')module.exports = function(app){ app.get('/', function(req, res){ var comments = JSON.parse(fs.readFileSync(__dirname + '/../comments.json')); res.render('index.ejs', comments); }); app.post('/', function(req, res){ console.log('here in post'); console.log(req.body) var name = req.body.name; var message = req.body.message; var newComment = {"name": name, "message": message}; var comments = JSON.parse(fs.readFileSync(__dirname + '/../comments.json')); comments.comments.push(newComment); fs.writeFileSync(__dirname + '/../comments.json', JSON.stringify(comments), 'utf8'); //redirect to a 'get' on '/' res.redirect('/'); }); app.get('/about', function(req, res){ res.render('about.html') });}
and server.js:
var express = require('express');var bodyParser = require('body-parser');var app = express();app.use(bodyParser.urlencoded())// routing configurationrequire('./router/main')(app);// ejs configurationapp.set('views', __dirname + '/views');app.set('view engine', 'ejs');app.engine('html', require('ejs').renderFile);// run the servervar server = app.listen(8080, function(){ console.log('Express server listening on port 8080');})