2017-01-17 133 views
1

試圖顯示從mongo db通過nodejs查詢到html index.html的數據。 腳本的功能是什麼?它打開服務器連接,連接到mongodb,並從webform與datapicker它顯示結果查詢,通過控制檯,我可以看到結果,它是完美的工作,現在我需要顯示的數據到網絡。nodejs res.json顯示在html

到目前爲止沒有結果。任何建議?

var express = require("express"); 
var app = express(); 
var router = express.Router(); 
var path = __dirname + '/views/'; 
var fs = require("fs"); 


const util = require('util') 

//lets require/import the mongodb native drivers. 
var mongodb = require('mongodb'); 

//We need to work with "MongoClient" interface in order to connect to a mongodb server. 
var MongoClient = mongodb.MongoClient; 

// Connection URL. This is where your mongodb server is running. 
var url = 'mongodb://localhost/klevin'; 


router.use(function (req,res,next) { 
    console.log("/" + req.method); 
    next(); 
}); 



router.get("/",function(req,res){ 

    res.sendFile(path + "index.html"); 



    var data_e_fillimit = req.param('start_time'); 
    //console.log(params.startDate) 
    console.log('Data e fillimit '+data_e_fillimit) 


    var data_e_mbarimit= req.param('endtime_time'); 
    //console.log(params.startDate) 
    console.log('Data e mbarimit '+data_e_mbarimit) 


// Use connect method to connect to the Server 
MongoClient.connect(url, function (err, db) { 

    if (err) { 
    console.log('Unable to connect to the mongoDB server. Error:', err); 
    } else { 
    //HURRAY!! We are connected. :) 
    console.log('Connection established to', url); 


    // Get the documents collection 
    var collection = db.collection('frames'); 

    //We have a cursor now with our find criteria 
    var cursor = collection.find({ 
     tv: 'tematv', 
     date_created: {"$gte": new Date(data_e_fillimit) , "$lte": new Date(data_e_mbarimit) }}); 

    //We need to sort by age descending 
    cursor.sort({_id: -1}); 

    //Limit to max 10 records 
    cursor.limit(50); 

    //Skip specified records. 0 for skipping 0 records. 
    cursor.skip(0); 


    //Lets iterate on the result 
    cursor.each(function (err, doc) { 

     if (err) { 

     console.log(err); 
     //res.json(err); 

     } else { 

     console.log('Fetched:', doc); 
     // res.json({ user: 'tobi' }) 



     } 
    }); 


    } 



}); 



}); 


/*router.get("/about",function(req,res){ 
    res.sendFile(path + "about.html"); 
}); 


router.get("/contact",function(req,res){ 
    res.sendFile(path + "contact.html"); 
});*/ 

app.use("/",router); 

/*app.use("*",function(req,res){ 
    res.sendFile(path + "404.html"); 
});*/ 

app.listen(3000,function(){ 
    console.log("Live at Port 3000"); 
}); 
+0

使用angularjs消耗鑑於API的,,。很簡單 –

回答

0

使用ejsnpm install ejs --save)包嘗試這樣的:

app.engine('html', require('ejs').renderFile);  
app.set('view engine', 'ejs'); 

app.get('/', function (req, res){ 
    res.render('index.html',{ 
     foo:bar 
    }); 
}); 

現在使用可以使用這個對象傳遞給index.html的