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. lambda,map,filter,reduce

    lambda 编程中提到的 lambda 表达式,通常是在需要一个函数,但是又不想费神去命名一个函数的场合下使用,也就是指匿名函数.返回一个函数对象. func = lambda x,y:x+y fu ...

  2. Input的size与maxlength属性的区别

    最近做项目用到input的size和maxlength属性,以前只顾用没有用心去看看这2个标签的区别,今天周末baidu了一下,有所理解.特记录于此!   <p>Name: <inp ...

  3. poj1860 Currency Exchange(spfa判断正环)

    Description Several currency exchange points are working in our city. Let us suppose that each point ...

  4. MongoDB整理笔记の走进MongoDB世界

    本人学习mongodb时间不长,但是鉴于工作的需要以及未来发展的趋势,本人想更深层的认识mongodb底层的原理以及更灵活的应用mongodb,边学边工作实践.  mongodb属于nosql中算是最 ...

  5. Tomcat与Web.xml配置

    1.编码配置 <Connector acceptCount=”100″ connectionTimeout=”20000″ disableUploadTimeout=”true” enableL ...

  6. javaScript入门之常用事件

    JS中的常用事件 onfocus/onblur:聚焦离焦事件,用于表单校验的时候比较合适. onclick/ondblclick:鼠标单击和双击事件 onkeydown/onkeypress:搜索引擎 ...

  7. 服务器控件数据回发实现IPostBackDataHandler需注意的

    我写的服务器控件(未完,模型如此) using System; using System.Collections.Generic; using System.Collections.Specializ ...

  8. mac 地址查询

    mac 地址由 6个字节(48bit)组成.前3个字节是厂商代码.输入厂商名称可查询相应的代码. http://standards.ieee.org/develop/regauth/oui/publi ...

  9. SpringMVC+Hibernate 使用 session.update(obj) 未更新的问题

    1.使用spring控制事务 2.使用session.update(obj)执行更新 spring事务配置: <bean id="transactionBese" class ...

  10. Java bean与Spring、Spring MVC关系

    Java Bean Java语言欠缺属性.事件.多重继承功能.所以,如果要在Java程序中实现一些面向对象编程的常见需求,只能手写大量胶水代码.Java Bean正是编写这套胶水代码的惯用模式或约定. ...