html ajax 调用节点 mongodb 失败

html ajax call node mongodb failed

嗨,我想使用 html ajax 调用 mongodb 并将结果填充到我的 html

客户端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"})

服务器 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); 

我输入 http://xx.xx.xx.xx:9000/dbcall 它调用 dbajax.html 但没有进一步发生。
我假设 html ajax 将调用 http://xx.xx.xx.xx:9000/db 和 return JSON 结果。

所以怎么了?我不想使用 Express 和其他框架。 谢谢

缺少响应可能有多种原因。您不处理 db.collection('Persons', ...) 的错误情况。您应该检查 err 是否填写在这里。我建议在不同的点添加一些 console.log() 语句,看看你能走多远。

编辑:我混淆了您正在调用的 URL,但上面的提示仍然有效。但是你也应该处理 fs.readFile(...) 可能出现的 err 情况。

您还可以在 dbajax.html 中添加一些日志语句,以在浏览器的开发人员控制台中查看进度(您可以按 F12 打开它)。