Pregunta

Estoy intentando autenticar antes de usar ajax para insertar en una base de datos

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

Aquí está mi código Node.js:

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' 
            }
  });
});

^^ esta parte funciona bien. Se trata de un texto modelo, puedo ir a localhost y ver la primera página.

La siguiente parte se supone que es donde sucede la inserción mongo. Esto me da un 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);
        });
    });
});

Lo que estoy tratando de hacer es insertar el objeto en stuff testCollection.

En este momento me estoy poniendo un 404 de encendido / db /

Estoy seguro que esto está muy mal. No creo que se supone que debo uso server.on, server.get no funciona bien. Por favor, asesorar, gracias.

¿Fue útil?

Solución

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.

Otros consejos

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(. . .);
    });
  });
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top