30

I am trying to create a simple form handler using express. I tried the code below for my form:

<form class="form"  action="/" method="post" name="regForm">              
    <div class="form-group">
        <input type="text" name="username" class="form-control" id="username" placeholder="Username">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
</form>

And here is my app.js code:

const port = 3000;

var express = require('express'),
    app = express(),
    server = require('http').createServer(app);
var bodyParser = require('body-parser');

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

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

app.use(bodyParser.json());

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

server.listen(port);

I keep getting the error "CANNOT POST /" after submitting the form. Am I missing something like a module?

dtem052996
  • 1,149
  • 2
  • 10
  • 15

7 Answers7

29

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
Dharman
  • 30,962
  • 25
  • 85
  • 135
Amulya Kashyap
  • 2,333
  • 17
  • 25
4

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.

Gabriel Arghire
  • 1,992
  • 1
  • 21
  • 34
3

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 ;

Samarth
  • 41
  • 1
1

Seems to work fine here.

The only bug I found is here:

extended: true;

You need to remove the semicolon at the end.

Also, you don't need action="/" in your form tag, just FYI.

chmod
  • 64
  • 6
  • 4
    While you are pointing at the issue, you are not giving a well written response. I suggest you update your post. – Ulrich Dohou Aug 17 '18 at 14:24
  • action="/" is not consequence-less. It can only be removed if the submitting page is also on the root of the server, which may not be true. – user37309 Mar 25 '20 at 03:07
1

Check for any trailing whitespace in your path strings. Sounds super simple but it took me two days to figure this was even possible. It seems that if your paths look like this

router.post('/foo ', (req, res)=> { // I hope you see it!
    res
        .status(200)
        .send({msg: 'Foo!'})
})

Instead of this

router.post('/foo', (req, res)=> {
    res
        .status(200)
        .send({msg: 'Foo!'})
})

You will get the "Cannot METHOD /PATH" error. It just so happens the browser is nice enough to truncate the trailing whitespace in it's error message as to not inconvinience you with unecessary information.

Stay safe kids, use "highlight whitespaces" in your editors for your own sanity.

Bar Akiva
  • 1,089
  • 1
  • 11
  • 23
0
You should call router instead of app
const router = express.Router();

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

router.post('/',function(req,res){
   var username = req.body.username;
   var htmlData = 'Hello:' + username;
   res.send(htmlData);
   console.log(htmlData);
});
ImranShaik
  • 33
  • 1
  • 9
0

Check if you have done one of the following:

  1. You probably have a repeating .post activity with the same name
  2. You probably have a repeating API in other modules with the same name
  3. The API is not registered in your server.js
  4. You may have entered a wrong name while calling from the controllers...