Cannot POST / error using express

Another Way is that we can use .route method provided by express

https://expressjs.com/en/guide/routing.html

Eg:

app.route("url")
   .get(function())

   .post(function());

remember to close the .route function using semi colon ;


In my case, I wasn't paying attention to the url I was posting from.

I had the page login http://localhost:5000/login which was posting and, if successful, renders the page account http://localhost:5000/account.

But, playing few times with these 2 pages, the link remained at http://localhost:5000/account but displayed the login page. So, when I was clicking the log in button which had a form with method = "post", I was getting the error Cannot POST /account.

So the fix was to correctly render the login page, by typing in the url of login page http://localhost:5000/login.


This way you should try

const port = 3000;

var express = require('express'),
    app = express();
var bodyParser = require('body-parser');

app.use(express.static(__dirname + '/public'));

app.use(bodyParser.urlencoded({
   extended: false
}));

app.use(bodyParser.json());

app.get('/', function(req, res){
  res.render('form');// if jade
  // You should use one of line depending on type of frontend you are with
  res.sendFile(__dirname + '/form.html'); //if html file is root directory
 res.sendFile("index.html"); //if html file is within public directory
});

app.post('/',function(req,res){
   var username = req.body.username;
   var htmlData = 'Hello:' + username;
   res.send(htmlData);
   console.log(htmlData);
});

app.listen(port);

Things you should keep in mind for future Ref :

  1. You were extending url encode to true
  2. You were not having any get request for your form
  3. You were using HTML named variable which is one of bad practices