express路由中使用mongoDB数据库(静态接口local..:8081)

var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017";
 
app.use(express.static('public'));
 
app.get('/index.htm', function (req, res) {
   res.sendFile( __dirname + "/" + "index.htm" );
})
 
app.get('/process_get', function (req, res) {   //路由跳转的位置
   // 输出 JSON 格式
   var response = {
       "first_name":req.query.first_name,//取值
       "last_name":req.query.last_name//取值
   };
   console.log(response);//在窗口能打印出来
   
   //连接数据库
    MongoClient.connect(url,{useNewUrlParser:true},function(err, db) {
		if (err) throw err;
		console.log("数据库已创建!");
	     var dbase=db.db("runoob");
		 dbase.collection("site"). find({}).toArray(function(err, result) { // 返回集合中所有数据
	        if (err) throw err;
	        console.log(result);//窗口打印数据
	        // 发送响应数据 
	        res.send(JSON.stringify(result));//查询的结果转换成字符串返回
	        db.close();//关闭数据库
	    });
});
})
 
var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("应用实例,访问地址为 http://%s:%s", host, port)
  //在cmd中打印
})

猜你喜欢

转载自blog.csdn.net/qq_41619567/article/details/84340285
今日推荐