nodejs res.json以html显示

时间:2017-01-17 10:05:54

标签: json node.js mongodb

尝试通过nodejs显示从mongo db查询的数据到html index.html。 脚本的作用是什么?它打开服务器连接,连接到mongodb,并从带有datapicker的webform显示结果查询,通过控制台我可以看到结果并且它工作正常,现在我需要将数据显示到web。

到目前为止没有结果。有什么建议吗?

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

1 个答案:

答案 0 :(得分: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的这个对象