用 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语言入门教程
https://www.youtube.com/playlist?list=PLY_qIufNHc293YnIjVeEwNDuqGo8y2Emx 感觉这个教程不错
- Part10-C语言环境初始化-一跃进入C大门lesson3
1.跳转到c代码 因为内存中的代码来自于垫脚石SRAM,他们是相同的. 采用绝对跳转方式来完成. 因为我们是从汇编代码跳转到c语言的程序,所以我们要提前准备一个main.c文件. 修改makefile ...
- Linux下chmod 777 修改权限
在linux操作系统下,使用shell命令来操作: 关于权限的问题用chmod命令来修改权限 -rw-r-r-- 1 root root 可参考:http://zhidao.baidu.com/lin ...
- js-day
1.克莱托指数 公式 :体重(kg) / (身高(m) * 身高(m)) < 20 : 偏瘦 > 20 <25 : 正常 > 25 : 偏旁 步骤: 1.输入体重(weight ...
- Orace开源的异步IO编程库,特点是接口非常简单
官网:https://oss.oracle.com/projects/libaio-oracle/,正如标题所说,非常简单了,不用多解释,请直接看头文件,其中aio_poll类似于poll,重要的结构 ...
- ABP源码uml类图
陆陆续续学习ABP框架有一段时间了,阳光铭睿的入门教程和HK Zhang的源码分析文章对我的学习帮助都很大.之所以会花这么大工夫去学习ABP.看ABP的源代码,一是因为本人对于DDD也非常有兴趣,AB ...
- 最全面的jackson json 技术
http://www.360doc.com/content/12/0429/09/7656232_207428466.shtml
- WindowsService服务安装脚本
安装脚本%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe D:\liuyl\WeiXinService\WindowsSe ...
- C# 读取Text文本,写入Text文本
//读取 private void showMess() { this.dataGridViewX2.Rows.Clear(); //将车辆信息一行行添加到datagreatview 里面 Strea ...
- 较为复杂的 GraphQL 查询实现
一.实现功能首页各类排行榜加载数据: 向下遍历子节点并展开: 1.展开过程中动态加载简介summary.书类bookType: 2.book对象上包裹Rank节点,描述book对象在不同排行榜下所处位 ...