用 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方式组织.并且客户端需要添加服务端引用才能使用(虽然看到网络上已经提供了这方面 ...
随机推荐
- 在CentOS6.x下安装Compiz——桌面立方体,特效种种
很多人貌似认为compiz必须要emerland,但事实上,没这个必要. compiz+gnome,实用,而又华丽,是个不错的选择. compiz需要显卡驱动,一般情况下不成问题(别忘了这是很新的ce ...
- xgboost 调参参考
XGBoost的参数 XGBoost的作者把所有的参数分成了三类: 1.通用参数:宏观函数控制. 2.Booster参数:控制每一步的booster(tree/regression). 3.学习目标参 ...
- CF835F Roads in the Kingdom
话说这是去年大爷的一道NOIP模拟赛题,对着大爷的代码看了一堂课的我终于把这题写掉了. 本题要求在基环树给定的环上删去一条边使剩下的树的直径最小,输出这个最小直径. 那么基环树可以画成这样子的: 有一 ...
- PHP文件的引用
require "文件名" 或 include("文件名") 区别:若所包含文件出现错误,include()产生一个警告,require会导致程序终止
- bootstrap页面效果图
<!DOCTYPE html><html lang="zh-cn"><head><meta charset="utf-8&quo ...
- JMeter的使用——ApacheJMeterTemporaryRootCA.crt的用法
在使用JMeter的时候,启动HTTP代理服务器弹出的那个提示框一直不知道是什么意思,刚刚弄明白了,在JMeter2.1之后,通过JMeter的代理服务器来访问https安全连接的网页的时候,浏览器会 ...
- C# LINQ(2)
前一章的代码LINQ都是以select结尾. 之前也说过可以group结尾. 那么怎么使用呢? 还是一样的条件,查询小于5大于0的元素 代码: ,,,,,,,,, }; var list = from ...
- 【SSO单点系列】(5):CAS4.0 单点流程序列图
刚过元旦假期,感觉自己好久没写博客了,今天更新一篇,主要是CAS 的一个流程图. ps: 这两张图 是直接从官网上找的,都是简单的英语,我这种英语四级没过都看得懂,大家应该没有压力. 1.CAS 基本 ...
- 从map中取出最大或最小value对应的key---多种写法
package com.yuwanlong.hashing; import java.util.ArrayList; import java.util.Collections; import java ...
- 5.EM