Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expressjs POST error: TypeError: Cannot read property 'title' of undefined

I tried a lot to figure out why this raises this error:

Configuring
Listening on 2000
TypeError: Cannot read property 'title' of undefined
   at /home/abdulsattar/learning/node/express/index.js:9:20

The index.js:

var express = require("express"),
    app = express.createServer();

app.get("/", function(req, res) {
  res.send('<form action="/new" method="post"><input type="text" name="title" /><input type="submit" /></form>');
});

app.post("/new", function(req, res) {
  res.send(req.body.title);
});

app.configure(function() {
  console.log("Configuring");
  app.use(express.bodyParser());
});

var port = process.env.PORT || 2000;

app.listen(port, function() {
  console.log("Listening on " + port);
});

I've read that express needs the bodyParser(). I used it above, but it always fails. I tried it on versions 2.5.8 and 2.5.8 (thinking that could be the problem) but it failed on both the versions. Is there something I'm missing?

like image 468
Abdulsattar Mohammed Avatar asked Dec 16 '22 03:12

Abdulsattar Mohammed


1 Answers

My hunch, try moving your app.configure statement before your app.get and app.post. The bodyParser middleware isn't being called. Also, to be safe add the enctype to the form, shouldn't be necessary, but regardless: application/x-www-form-urlencoded.

Let me know...

like image 193
JP Richardson Avatar answered Dec 20 '22 17:12

JP Richardson