Search code examples
ajaxnode.jsmongodbcall

html ajax call node mongodb failed


HI I would like to use html ajax call mongodb and populate the results into my html

client html (dbajax.html):

$.ajax({
  url: 'http://xx.xx.xx.xx:9000/db',
  type: 'get',
  dataType: 'jsonp',
  jsonp: 'jsonp', // mongod is expecting the parameter name to be called "jsonp"})

Server dbserver.js

http.createServer(function (request,response)
{  
    // serve site
    if (request.url === "/")
    {
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
    }
  if (request.url === "/db")
    {
       console.log("db");
        MongoClient.connect("mongodb://localhost:27017/MyDb2", function (err, db) {

       db.collection('Persons', function (err, collection) {

     collection.find().toArray(function(err, items) {
        if(err) throw err;    
        console.log(items);    
        response.writeHead(200, {"Content-Type:": "application/json"}); 
        var submittedPost = {};
        submittedPost['message'] = 'Proof that Node and Mongo are          working..';
        response.write( "_wrapper('" );
        response.write( JSON.stringify(items) );
        response.write( "')");              
        response.end();
    });

});

}); 
    }
      if (request.url === "/dbcall"){
          console.log("dbcall");
           fs.readFile('./dbajax.html', function (err, html) 
      {
        //response.writeHeader(200, {"Content-Type": "text/html"});  
       response.write(html);  
       response.end();
    }
                )


  }
    //response.end(); 
}).listen(9000); 

I type http://xx.xx.xx.xx:9000/dbcall it calls dbajax.html but nothing happen further.
I assume the html ajax will call http://xx.xx.xx.xx:9000/db and return the JSON result.

So what is wrong? I don't want to use Express and other frameworks. Thanks


Solution

  • There may be multiple reasons for the missing response. You don't handle the error condition of db.collection('Persons', ...). You should check if the err is filled here. And I suggest to add some console.log() statements at different points to see how far you get.

    EDIT: I mixed up the URL you are calling but the hints above are still valid. But you should also handle the possible err condition of fs.readFile(...).

    You can also add some log statements to your dbajax.html to watch the progress within the developer console of your browser (you can open it by pressing F12).