2

The full code is following - pretty simply i wanna add, delete or update posts - when i do one of the things by them self it works but togther it breaks

Iv'd searched alot in the NodeJS MySQL which i use to query the database

var mysql = require('mysql');

var connection = mysql.createConnection({
  host : 'localhost',
  port : 3306,
  database: 'nodeproject',
  user : 'noderoot',
  password : 'default'
});

var express = require('express');
var http = require('http');
var path = require('path');
var exphbs  = require('express3-handlebars');
var qs = require('querystring');

var app = express();

app.set('port', process.env.PORT || 8000);
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

configQuery = function() {
  connection.config.queryFormat = function (query, values) {
  if (!values) return query;
  return query.replace(/\:(\w+)/g, function (txt, key) {
    if (values.hasOwnProperty(key)) {
      return this.escape(values[key]);
    }
    return txt;
  }.bind(this));
  };
}


index = function(req, res){
    /*connection.connect(function(err){
      if(err != null) {
        res.end('Error connecting to mysql:' + err+'\n');
      }
    });*/

    connection.query("SELECT * FROM posts", function(err, rows){
      if(err != null) {
        res.end("Query error:" + err);
      } else {
        var myOuterRows = [];
        for (var i = 0; i < rows.length; i++) {
            var myRows = rows[i];
            myOuterRows.push(myRows);
        };

        res.render('index', { 
            title: 'Express Handlebars Test',
            posts: myOuterRows
        });
      }
    });
};

addpost = function(req, res) {
    var post  = {
        id: req.body.post.id, 
        postTitle: req.body.post.postTitle, 
        postContent: req.body.post.postContent,
        published: req.body.post.published
    };

    connection.query('INSERT INTO posts SET ?', post, function(err, result) {
        console.log("Neat! you entered a post");
    });

    res.redirect("/");
}
editpost = function(req, res) {

    configQuery();

    var edit = {
        id: req.body.editpost.id, 
        postTitle: req.body.editpost.postTitle, 
        postContent: req.body.editpost.postContent
    };


    var queryTitle = connection.query("UPDATE posts SET ?", edit, function(err, result) {
        console.log("Neat! you editted a post")
    });

    res.redirect("/");
}
deletepost = function(req, res) {

    configQuery();

    var deleteThis  = {
        id: req.body.deletepost.id
    };

    console.log(deleteThis);

    var queryDelete = connection.query("DELETE FROM posts WHERE id = :id", {
        id: deleteThis.id
    });

    res.redirect("/");
}

app.get('/', index);

app.post('/', addpost);
app.post('/', editpost);
app.post('/', deletepost);

//app.get('/list', list);

http.createServer(app).listen(8000, function(){
  console.log('Express server listening on port ' + app.get('port'));


});

The error i get is following:

500 TypeError: Cannot read property 'id' of undefined
at editpost (C:\dev\ExpressHbsMysql\app.js:96:24)
at callbacks (C:\dev\ExpressHbsMysql\node_modules\express\lib\router\index.js:164:37)
at param (C:\dev\ExpressHbsMysql\node_modules\express\lib\router\index.js:138:11)
at pass (C:\dev\ExpressHbsMysql\node_modules\express\lib\router\index.js:145:5)
at Router._dispatch (C:\dev\ExpressHbsMysql\node_modules\express\lib\router\index.js:173:5)
at Object.router (C:\dev\ExpressHbsMysql\node_modules\express\lib\router\index.js:33:10)
at next (C:\dev\ExpressHbsMysql\node_modules\express\node_modules\connect\lib\proto.js:193:15)
at Object.methodOverride [as handle] (C:\dev\ExpressHbsMysql\node_modules\express\node_modules\connect\lib\middleware\methodOverride.js:48:5)
at next (C:\dev\ExpressHbsMysql\node_modules\express\node_modules\connect\lib\proto.js:193:15)
at C:\dev\ExpressHbsMysql\node_modules\express\node_modules\connect\lib\middleware\urlencoded.js:83:7
Simon Dragsbæk
  • 2,367
  • 3
  • 30
  • 53
  • i couldn't read much but one thing i notice is why would you map one url to multiple handlers? like `/` with type `post` is mapped to `editpost`, `deletepost`, `addpost` – user2009750 Apr 12 '14 at 12:59
  • Have you tried google's node-debug and put breakpoints at/above the lines of the error and see what objects are there, what objects should be there etc and then trace back where it goes wrong? Oh, and use only one app.VERB() per url and do the conditional workflow in that one function. – Pengtuzi Apr 12 '14 at 13:02
  • @pronox http://stackoverflow.com/questions/5710358/how-to-get-post-query-in-express-node-js id followed this example of how to do post form in node – Simon Dragsbæk Apr 12 '14 at 13:03
  • @Pengtuzi havn't tried that? got a link? – Simon Dragsbæk Apr 12 '14 at 13:05
  • @SimonPertersen what i want to say is kindof long as i posted it as an answer check this it might help – user2009750 Apr 12 '14 at 13:05
  • @SimonPertersen yes your code allow should work as you followed that stack question but i mean expose each of your handler at different url . – user2009750 Apr 12 '14 at 13:07

1 Answers1

2

Where should it go?

app.post('/', addpost);
app.post('/', editpost);
app.post('/', deletepost);

To addpost or to editpost or to deletepost

As far as i can tell from your code i suggest you keep different urls for each handler that way you will tell which handler to call, right now all your post requests call first handler which is addpost

Map your handlers like this

app.post('/post/add', addpost);
app.post('/post/edit', editpost);
app.post('/post/delete', deletepost);

Next in your forms or if your are using ajax post your addrequest to '/post/add', editrequest to /post/edit and so on.

user2009750
  • 3,169
  • 5
  • 35
  • 58