I recently turned to a simple guide on creating an Express server ( https://codeforgeek.com/2014/06/express-nodejs-tutorial/ ).
I am trying to extend the code from this tutorial so that I can respond to post requests. I want to do this by updating the json file (which is populated with "user comments" and then redraws to '/'
./server.js:
var express = require('express'); var app = express(); // routing configuration require('./router/main')(app); // ejs configuration app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.engine('html', require('ejs').renderFile); // run the server var server = app.listen(8080, function(){ console.log('Express server listening on port 8080'); });
./router/main.js(routers):
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'); 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.push(newComment); fs.writeFileSync(__dirname + '/../comments.json', comments, 'utf8');
./views/index.ejs:
<div> <div> <h1> Joe Forum </h1> <a href='/about'> (about) </a> </div> <div> <ul> <% comments.forEach( function(comment){ %> <li> <%= comment.name %> : <%= comment.message %> </li> <% }); %> </ul> </div> <h2> Enter a new comment </h2> <form action='/' method="post"> Enter your name: <input type='text' name='name'> <br><br> Enter your message: <input type='textarea' name='message'> <br><br> <input type='submit' value='Submit'> <form> </div>
./comments.json:
{ "comments": [ {"name":"Joe", "message" : "What advantages does Node.js afford the web developer?"}, {"name": "John", "message": "Asynchronous IO helps us to keep our pages responsive even if the server is fetching data"} ] }
When I try to submit a new comment from my form, all I see is the following:
"Cannot POST /"
Can someone explain why I can get this error? Thanks