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,210
  • 3
  • 29
  • 51
  • 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` – KKK 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 – KKK 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 . – KKK 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.

KKK
  • 3,039
  • 5
  • 32
  • 56
  • But what if they are on the same page - does that matter? the url what does it do? – Simon Dragsbæk Apr 12 '14 at 13:06
  • actually if you are editing then post your form to url with post handler let me update my answer – KKK Apr 12 '14 at 13:08
  • Else i would in each form element set the form action to the url? – Simon Dragsbæk Apr 12 '14 at 13:10
  • @SimonPertersen it does not matter what page is rendering your view all that matters is keep your handlers at the right place. Then send requests to corresponding handler irrespective of the view. – KKK Apr 12 '14 at 13:12
  • how are you handling your form action? – KKK Apr 12 '14 at 13:15
  • just by a native form element - i got delete and add to work simultaneously i think the addpost have ran into another problem – Simon Dragsbæk Apr 12 '14 at 13:16
  • @SimonPertersen try using javascript in for posting your forms, so if some is adding a post you'll know where to send request, if someone is clicking delete post button you should then post your request to delete request and the same way you handle your editrequest. – KKK Apr 12 '14 at 13:21
  • 1
    Ty for help - clean an easy respons – Simon Dragsbæk Apr 12 '14 at 13:24