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 的例子的更多相关文章

  1. 通过配置web.config使WCF向外提供HTTPS的Restful Service

    如何通过WCF向外提供Restful的Service请看如下链接 http://www.cnblogs.com/mingmingruyuedlut/p/4223116.html 那么如何通过对web. ...

  2. 测试必须学spring RESTful Service(上)

    文末我会说说为什么测试必须学spring. REST REST,是指REpresentational State Transfer,有个精辟的解释什么是RESTful, 看url就知道要什么 看met ...

  3. spring如何创建RESTful Service

    REST REST,是指REpresentational State Transfer,有个精辟的解释什么是RESTful, 看url就知道要什么 看method就知道干什么 看status code ...

  4. Python flask 基于 Flask 提供 RESTful Web 服务

    转载自 http://python.jobbole.com/87118/ 什么是 REST REST 全称是 Representational State Transfer,翻译成中文是『表现层状态转 ...

  5. JAVA格物致知基础篇:用JAX-RS和Jersey打造RESTful Service

    随着服务器的处理能力越来越强,业务需求量的不断累积,越来越多的公司开始从单一服务器,单一业务承载变成了多服务器,多业务承载的快速扩展的过程中.传统的方法很难满足和应付这种业务量的增长和部署方式的改变. ...

  6. 构建基于WCF Restful Service的服务

    前言 传统的Asmx服务,由于遵循SOAP协议,所以返回内容以xml方式组织.并且客户端需要添加服务端引用才能使用(虽然看到网络上已经提供了这方面的Dynamic Proxy,但是没有这种方式简便), ...

  7. 基于.Net FrameWork的 RestFul Service

    关于本文 这篇文章的目的就是向大家阐述如何在.net framework 4.0中创建RestFul Service并且使用它. 什么是web Services,什么是WCF 首先讲到的是web Se ...

  8. Wcf Restful Service服务搭建

    目的 使用Wcf(C#)搭建一个Restful Service 背景 最近接到一个项目,客户要求使用Restful 方式接收到数据,并对数据提供对数据的统计显示功能,简单是简单,但必须要使用Restf ...

  9. WCF Restful Service的服务

    构建基于WCF Restful Service的服务 前言 传统的Asmx服务,由于遵循SOAP协议,所以返回内容以xml方式组织.并且客户端需要添加服务端引用才能使用(虽然看到网络上已经提供了这方面 ...

随机推荐

  1. c语言解二元二次方程组

    设a和b是正整数 a+b=30 且a*b=221 求a和b的值 思路就是穷举a和b的值,每次得到a和b的一个值,看是否同时满足a+b=30且a*b=221,如果满足,那么就输出. 那么a和b的的取值范 ...

  2. 30.MIN() 函数

    MIN() 函数 MIN 函数返回一列中的最小值.NULL 值不包括在计算中. SQL MIN() 语法 SELECT MIN(column_name) FROM table_name 注释:MIN ...

  3. Python的split()函数

    手册中关于split()用法如下: str.split(sep=None, maxsplit=-1)     Return a list of the words in the string, usi ...

  4. Struts2获取Action中的数据

    当我们用Struts2框架开发时,经常有要获取jsp页面的数据或者在jsp中获取后台传过来的数据(Action),那么怎么去获取自己想要的数据呢? 后台获取前端数据: 在java程序中生成要获取字段的 ...

  5. DB2 添加license

    DB2 - DB2COPY1 - DB2-0 服务不能启动报的错是这样的:Microsoft Management Console   Windows 不能在 本地计算机 启动 DB2 - DB2.有 ...

  6. WP REST API: 设置和使用OAuth 1.0a Authentication(原文)

    In the previous part of the series, we set up basic HTTP authentication on the server by installing ...

  7. Linux服务器其中一个磁盘满了怎么办?在不做磁盘扩容的情况下,一个软连接就搞定。

    适用环境要求:Linux系统及服务器.有管理员权限.存在多余空间的磁盘例如下图中"/home"在磁盘sda5中与"/"不属于同一块磁盘: 1.首先转移正在使用的 ...

  8. 扩展卢卡斯定理(Exlucas)

    题目链接 戳我 前置知识 中国剩余定理(crt)或扩展中国剩余定理(excrt) 乘法逆元 组合数的基本运用 扩展欧几里得(exgcd) 说实话Lucas真的和这个没有什么太大的关系,但是Lucas还 ...

  9. pdo 预处理

      <?php /* * pdo 预处理sql */ $dsn = "mysql:dbname=0328;host=localhost"; $username = " ...

  10. 黑色主题-darkgreentrip

    /* 整个页面 */ home,#main { margin:0px 0px 0px 0px; background:rgb(9, 9, 9, 0.9); } /* 头部高度 */ header { ...