用 Koa 提供 Restful service 和查询 MongoDB 的例子
const path = require('path');
const Koa = require('koa');
const app = new Koa();
const compose = require('koa-compose');
const router = require('koa-router')();
const bodyParser = require('koa-bodyparser');
const static = require('koa-static');
const static_root = static(path.join(__dirname + "/../client/dist")); // Point to the root of web app
const MongoClient = require('mongodb').MongoClient;
const DB_CONN_STR = 'mongodb://localhost:27017/sample';
// Variable for storing query result
var result = null;
// ********************************** Koa part **********************************
// Error handler
const handler = async (ctx, next) => {
try {
await next();
} catch (err) {
ctx.response.status = err.statusCode || err.status || 500;
ctx.response.type = 'html';
ctx.response.body = '<h2>Something wrong, please contact administrator.</h2>';
// ctx.app.emit('error', err, ctx);
}
};
// Logger
const logger = async (ctx, next) => {
console.log(`${ctx.request.method} ${ctx.request.url}`);
await next();
};
const middlewares = compose([handler, bodyParser(), router.routes(), logger, static_root]);
app.use(middlewares);
// ********************************** DB part **********************************
// Common function to connect mongoDB, and run the callback function
var runDb = function (callback) {
MongoClient.connect(DB_CONN_STR, function (err, db) {
if (err) {
console.log("Error: ", err);
db.close();
process.exit(1);
} else {
callback(db);
db.close();
}
});
}
// Data for insert
var data1 = [
{ "name": "AAA", "age": 1 },
{ "name": "BBB", "company": "Google Co." }
];
// Insert function, just for testing
var insertData = function (db) {
db.collection("table1").insert(data1, function (err, result) {
if (err) {
console.log("Error: ", err);
return;
}
});
}
// Query function
var queryData = function (db) {
db.collection("table1").find({}).toArray(function (err, docs) {
if (err) {
console.log("Error: ", err);
} else {
result = docs;
}
});
}
// Call the db to insert data
runDb(insertData);
// ********************************** Controller part **********************************
// Redirect the root to Angular index.html
router.get('/', async (ctx, next) => {
ctx.response.redirect('/index.html');
});
// Just an api for testing
router.get('/ui-api/hello/:name', async (ctx, next) => {
// just for sample
var name = ctx.params.name;
ctx.response.body = `<h1>Hello, ${name}!</h1>`;
});
// Just an api for testing
router.get('/ui-api/data', async (ctx, next) => {
runDb(queryData);
ctx.response.type = 'json';
// ctx.set("Access-Control-Allow-Origin", "*"); // Disable cross origin
ctx.response.body = result;
});
// ********************************** Startup part **********************************
let port = 80;
app.listen(port);
console.log('app started at port : ' + port);
用 Koa 提供 Restful service 和查询 MongoDB 的例子的更多相关文章
- 通过配置web.config使WCF向外提供HTTPS的Restful Service
如何通过WCF向外提供Restful的Service请看如下链接 http://www.cnblogs.com/mingmingruyuedlut/p/4223116.html 那么如何通过对web. ...
- 测试必须学spring RESTful Service(上)
文末我会说说为什么测试必须学spring. REST REST,是指REpresentational State Transfer,有个精辟的解释什么是RESTful, 看url就知道要什么 看met ...
- spring如何创建RESTful Service
REST REST,是指REpresentational State Transfer,有个精辟的解释什么是RESTful, 看url就知道要什么 看method就知道干什么 看status code ...
- Python flask 基于 Flask 提供 RESTful Web 服务
转载自 http://python.jobbole.com/87118/ 什么是 REST REST 全称是 Representational State Transfer,翻译成中文是『表现层状态转 ...
- JAVA格物致知基础篇:用JAX-RS和Jersey打造RESTful Service
随着服务器的处理能力越来越强,业务需求量的不断累积,越来越多的公司开始从单一服务器,单一业务承载变成了多服务器,多业务承载的快速扩展的过程中.传统的方法很难满足和应付这种业务量的增长和部署方式的改变. ...
- 构建基于WCF Restful Service的服务
前言 传统的Asmx服务,由于遵循SOAP协议,所以返回内容以xml方式组织.并且客户端需要添加服务端引用才能使用(虽然看到网络上已经提供了这方面的Dynamic Proxy,但是没有这种方式简便), ...
- 基于.Net FrameWork的 RestFul Service
关于本文 这篇文章的目的就是向大家阐述如何在.net framework 4.0中创建RestFul Service并且使用它. 什么是web Services,什么是WCF 首先讲到的是web Se ...
- Wcf Restful Service服务搭建
目的 使用Wcf(C#)搭建一个Restful Service 背景 最近接到一个项目,客户要求使用Restful 方式接收到数据,并对数据提供对数据的统计显示功能,简单是简单,但必须要使用Restf ...
- WCF Restful Service的服务
构建基于WCF Restful Service的服务 前言 传统的Asmx服务,由于遵循SOAP协议,所以返回内容以xml方式组织.并且客户端需要添加服务端引用才能使用(虽然看到网络上已经提供了这方面 ...
随机推荐
- C++ 输出精度和输出小数点位数
有时候需要调节小数点的精度或者位数 #include<iostream> #include<iomanip> using namespace std; //设置数据精度 set ...
- jQuery--修改表单数据并提交
目的: 点击'编辑',弹出对话框,修改数据. 主要知识点: prevAll(),获取同级别本元素前面的所有元素. 代码: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...
- RocketMq2
- [转]asp.net使用uploadify上传出现的IO Error问题
原文链接:http://blog.csdn.net/w3031213101/article/details/6335878 解决方法:1.uploadify控件的自定义size必须调整大小,即属性:s ...
- Reading——The Non-Designer's Design Book
看这本书的时候真的好恨没有CS7在手><,不然我百度几张图来模拟下,体验下设计的快感. 人们总是很容易注意到在他们潜意识里存在的东西,比如说这个图: 我们很容易联想到微信,但是3 ...
- 7.python实现高效端口扫描器之nmap模块
对于端口扫描,使用的最多的就是nmap这个工具,不想python已经强大到,提供了nmap这个扫描端口的模块. 本片文章主要介绍nmap模块的两个常用类: PortScanner()类,实现一个nma ...
- MVC下的cshtml和aspx页面
MVC中的aspx页面是System.Web.Mvc.ViewPage类的实例. 表示将视图呈现为 Web 窗体页所需的属性和方法. 继承层次结构 System.Object System.Web.U ...
- cad转shapefile文件
private ESRI.ArcGIS.Controls.AxTOCControl axTOCControl1; private ESRI.ArcGIS.Controls.AxLicenseContr ...
- 解决jquery操作checkbox火狐下第二次无法勾选问题
最近在学习jQuery(版本jquery-1.9.1.js),要求用jQuery实现全选/全不选.反选,在IE(IE8)中没有问题,但在火狐浏览器中调试的时候出现了一些小问题,达不到效果. html代 ...
- JQuery.validator插件使用
首先给变量validator赋值 var validator =$('#test').validate({validate构造 }); 接着调用 $('#test').valid() 会使用上面的验证 ...