ajax post to node.js express app?

Question!

I'm trying to authenticate before using ajax to insert into a database

$('#button').click(function () {       
  $.post('/db/', { 
   stuff: { "foo" : "bar"}
  }, callback, "json");
});

Here's my node.js code:

server.get('/', function(req,res){
console.log(res);
  res.render('index.ejs', {
    locals : { 
              header: '#Header#'
             ,footer: '#Footer#'
             ,title : 'Page Title'
             ,description: 'Page Description'
             ,author: 'Your Name'
             ,analyticssiteid: 'XXXXXXX' 
            }
  });
});

^^ this part works ok. It comes from a boilerplate, I can go to localhost and see the front page.

This next part is supposed to be where the mongo insert happens. This gives me a 404.

server.on('/db/', function(req,res){
    console.log(req);
    console.log(res);
    var db = new mongo.Db( 'dbname' , new mongo.Server( 'localhost', 20003, {}), {});   
    db.open(function (err) {
        db.collection('testCollection', function (err, collection) {
            collection.insert(res.stuff);
        });
    });
});

What I'm trying to do is insert the object stuff into testCollection.

Right now I'm getting a 404 on /db/

I'm sure this is very wrong. I don't think I'm supposed to use server.on, server.get doesn't work either. Please advise, thanks.



Answers

you also should be authenticating the db connect and shouldn't be reconnecting to the db on each request

var db = new mongo.Db( 'dbname' , new mongo.Server( 'localhost', 20003, {}), {});
db.authenticate(user, password, function({ // callback }));

server.post('/db/', function(req,res){
  db.open(function (err) {
    db.collection('testCollection', function (err, collection) {
      collection.insert(. . .);
    });
  });
});


Since you're expecting a post, your /db/ handler should be defined in a server.post method. You're getting a 404 because the server doesn't have a route defined for the combination of POST and /db/.

By : Dave Ward


This video can help you solving your question :)
By: admin