문제

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.

도움이 되었습니까?

해결책

You have to use server.post, since you're doing a POST request via jQuery.

server.on will add a event listener to the server, in this case for the non-existent /db/ event, which never gets triggered by anything.

Please take your time and make sure to read the express.js Guide, the Node.js API Docs might come in handy too.

다른 팁

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/.

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(. . .);
    });
  });
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top