利用koa打造restful API
概述
最近学习利用koa搭建API接口,小有所得,现在记录下来,供以后开发时参考,相信对其他人也有用。
就目前我所知道的而言,API有2种,一种是jsonp这种API,前端通过ajax来进行跨域请求获得数据;另一种是restful API,前端通过fetch或者axios进行cors请求来获得数据。
本篇博文记录我用koa打造的jsonp API。
可以先查看我的上一篇文章:利用koa打造jsonp API。
参考资料:《Koa2进阶学习笔记》,KOA docs
restful API
其实搭建restful API很简单,引入cors中间件即可,不需要设置请求头为Access-Control-Allow-Origin,这个中间件会自动帮我们设置。我们先引入中间件,然后重开一个路由存放restful API即可,代码如下:
'use strict'
const Koa = require('koa');
const logger = require('koa-logger');
const Router = require('koa-router');
const cors = require('@koa/cors');
const app = new Koa();
app.use(logger());
app.use(cors());
// 子路由1:主页
let routerHome = new Router();
routerHome.get('/', async (ctx) => {
ctx.body = '欢迎欢迎!';
})
// 子路由2:jsonp api
let routerJsonp = new Router();
routerJsonp.get('/data1', async (ctx) => {
let cb = ctx.request.query.callback;
ctx.type = 'text';
ctx.body = cb + '(' + '"数据"' + ')';
})
// 子路由3:restful api
let routerRest = new Router();
routerRest.get('/data1', async (ctx) => {
ctx.body = 'rest数据';
})
// 装载所有路由
let router = new Router();
router.use('/', routerHome.routes(), routerHome.allowedMethods());
router.use('/jsonp', routerJsonp.routes(), routerJsonp.allowedMethods());
router.use('/restful', routerRest.routes(), routerRest.allowedMethods());
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000, () => {
console.log('koa starts at port 3000!');
})
然后利用下面的请求代码,就会在控制台输出“rest数据”。
$.ajax({
url : 'http://localhost:3000/restful/data1',
type : 'get',
success : function(res){
console.log(res);
},
error: function() {
alert("网络出现错误,请刷新!");
}
});
改进
不得不说,我们的api是非常简陋的,我们考虑对它做如下改进:
- 支持post请求。这个很好办,在路由那里添加post方法即可。
- 支持yaml数据导入,然后通过api,把数据作为resonse发送出去。这个需要2步操作,第一步用node导入并解析yaml数据为对象,第二步把对象转化为字符串传递出去。第一步需要用到fs库和yamljs库,第二步需要用到JSON.stringify方法。具体代码如下:
首先支持post请求:
'use strict'
const Koa = require('koa');
const logger = require('koa-logger');
const Router = require('koa-router');
const cors = require('@koa/cors');
const app = new Koa();
app.use(logger());
app.use(cors());
// 子路由1:主页
let routerHome = new Router();
routerHome.get('/', async (ctx) => {
ctx.body = '欢迎欢迎!';
})
// 子路由2:jsonp api
let routerJsonp = new Router();
routerJsonp.get('/data1', async (ctx) => {
let cb = ctx.request.query.callback;
ctx.type = 'text';
ctx.body = cb + '(' + '"数据"' + ')';
}).post('/data1', async (ctx) => {
let cb = ctx.request.query.callback;
ctx.type = 'text';
ctx.body = cb + '(' + '"数据"' + ')';
})
// 子路由3:restful api
let routerRest = new Router();
routerRest.get('/data1', async (ctx) => {
ctx.body = 'rest数据';
}).post('/data1', async (ctx) => {
ctx.body = 'rest数据';
})
// 装载所有路由
let router = new Router();
router.use('/', routerHome.routes(), routerHome.allowedMethods());
router.use('/jsonp', routerJsonp.routes(), routerJsonp.allowedMethods());
router.use('/restful', routerRest.routes(), routerRest.allowedMethods());
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000, () => {
console.log('koa starts at port 3000!');
})
然后我们新建jsonp.data1.yaml文件作为jsonp API的原始数据,新建restful.data1.yaml作为restful API的原始数据。
//jsonp.data1.yaml
api: "jsonp"
info:
version: "0.0.1"
title: test for jsonp
//restful.data1.yaml
api: "restful"
info:
version: "0.0.1"
title: test for restful
然后我们添加fs库(node自带,不需要install)和yamljs库进行导入和解析yaml文件,并且用JSON.stringify方法把json对象转化为字符串:
'use strict'
const Koa = require('koa');
const logger = require('koa-logger');
const Router = require('koa-router');
const cors = require('@koa/cors');
const fs = require('fs');
const YAML = require('yamljs');
const app = new Koa();
app.use(logger());
app.use(cors());
// 子路由1:主页
let routerHome = new Router();
routerHome.get('/', async (ctx) => {
ctx.body = '欢迎欢迎!';
})
// 子路由2:jsonp api
let routerJsonp = new Router();
routerJsonp.get('/data1', async (ctx) => {
let cb = ctx.request.query.callback;
ctx.type = 'text';
ctx.body = cb + '(' + JSON.stringify(YAML.parse(fs.readFileSync('./jsonp.data1.yaml').toString())) + ')';
}).post('/data1', async (ctx) => {
let cb = ctx.request.query.callback;
ctx.type = 'text';
ctx.body = cb + '(' + JSON.stringify(YAML.parse(fs.readFileSync('./jsonp.data1.yaml').toString())) + ')';
})
// 子路由3:restful api
let routerRest = new Router();
routerRest.get('/data1', async (ctx) => {
ctx.body = YAML.parse(fs.readFileSync('./restful.data1.yaml').toString());
}).post('/data1', async (ctx) => {
ctx.body = YAML.parse(fs.readFileSync('./restful.data1.yaml').toString());
})
// 装载所有路由
let router = new Router();
router.use('/', routerHome.routes(), routerHome.allowedMethods());
router.use('/jsonp', routerJsonp.routes(), routerJsonp.allowedMethods());
router.use('/restful', routerRest.routes(), routerRest.allowedMethods());
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000, () => {
console.log('koa starts at port 3000!');
})
用前面类似的方法进行请求,可以看到返回了如下数据,并且支持了post请求。
//jsonp接口
Object {api: "jsonp", info: Object}
//restful接口
Object {api: "restful", info: Object}
其它
到这里就全部完成了,我尽量一点一点地浅显的写出来。实际上还有更多可以优化的地方:
- 支持匹配各种模糊的url路径。
- 支持对传入参数进行处理。
- 支持https。
而且我们再一次看到,学习koa其实就是各种中间件和api的学习罢了。
最后写一下需要install的库:(虽然可以通过require推测出来)
"@koa/cors": "^2.2.1",
"koa": "^2.5.1",
"koa-bodyparser": "^4.2.0",
"koa-logger": "^3.2.0",
"koa-router": "^7.4.0",
"yamljs": "^0.3.0"
本文代码存放在我的github的blog_server仓库的demo文件夹里面。
利用koa打造restful API的更多相关文章
- 利用koa打造jsonp API
概述 最近学习利用koa搭建API接口,小有所得,现在记录下来,供以后开发时参考,相信对其他人也有用. 就目前我所知道的而言,API有2种,一种是jsonp这种API,前端通过ajax来进行跨域请求获 ...
- Spring Boot入门系列(二十)快速打造Restful API 接口
spring boot入门系列文章已经写到第二十篇,前面我们讲了spring boot的基础入门的内容,也介绍了spring boot 整合mybatis,整合redis.整合Thymeleaf 模板 ...
- Springboot 如何加密,以及利用Swagger2构建Restful API
先看一下使用Swagger2构建Restful API效果图 超级简单的,只需要在pom 中引用如下jar包 <dependency> <groupId>io.springfo ...
- 利用Django实现RESTful API(一)
RESTful API现在很流行,这里是它的介绍 理解RESTful架构和 RESTful API设计指南.按照Django的常规方法当然也可以实现REST,但有一种更快捷.强大的方法,那就是 Dja ...
- 自定义分布式RESTful API鉴权机制
微软利用OAuth2为RESTful API提供了完整的鉴权机制,但是可能微软保姆做的太完整了,在这个机制中指定了数据持久化的方法是用EF,而且对于用户.权限等已经进行了封装,对于系统中已经有了自己的 ...
- Flask RESTful API搭建笔记
之前半年时间,来到项目的时候,已经有一些东西,大致就是IIS+MYSQL+PHP. 所以接着做,修修补补,Android/iOS与服务器数据库交换用PHP, Web那边则是JS+PHP,也没有前后端之 ...
- DICOM医学图像处理:深入剖析Orthanc的SQLite,了解WADO & RESTful API
背景: 上一篇博文简单翻译了Orthanc官网给出的CodeProject上“利用Orthanc Plugin SDK开发WADO插件”的博文,其中提到了Orthanc从0.8.0版本之后支持快速查询 ...
- Spring Boot 入门系列(二十二)使用Swagger2构建 RESTful API文档
前面介绍了如何Spring Boot 快速打造Restful API 接口,也介绍了如何优雅的实现 Api 版本控制,不清楚的可以看我之前的文章:https://www.cnblogs.com/zha ...
- Node.js实现RESTful api,express or koa?
文章导读: 一.what's RESTful API 二.Express RESTful API 三.KOA RESTful API 四.express还是koa? 五.参考资料 一.what's R ...
随机推荐
- Tkinter添加图片
Tkinter添加图片的方式,与Java相似都是利用label标签来完成的: 一.默认的是gif的格式,注意将png后缀名修改为gif还是无法使用,文件格式依然错误. photo = PhotoIma ...
- Elastic serarch 安装
1.安装 1.1下载最新的 elasticsearch-6.5.4.tar.gz 1.2解压 tar -zxvf elasticsearch-6.5.4.tar.gz 1.3 创建用户 elastic ...
- 类型转化&WCF不同binding的区别
需要使用队列时并且涉及多线程时使用ConcurrentQueue 这个性内比自己使用Queue并且配合lock要好很多 calcFactory = new ChannelFactory<ICal ...
- 作用域的一些说明,static关键词
作用域的一些说明 变量分为全局变量和局部变量.学过C语言的童鞋都知道,全局变量的作用域是整个整个文件.在即使在函数内部也有效,但在php中,如果在函数中使用全局变量,php会认为这个变量没有定义.如果 ...
- HDU 1536 S-Nim (组合游戏+SG函数)
题意:针对Nim博弈,给定上一个集合,然后下面有 m 个询问,每个询问有 x 堆石子 ,问你每次只能从某一个堆中取出 y 个石子,并且这个 y 必须属于给定的集合,问你先手胜还是负. 析:一个很简单的 ...
- MongoDB常用命令总结
查看数据库 show dbs; 选择某个库 use db; 查看库下的表(暂且说成是表,mongodb中称表问文档) show collections; 插入数据 db.table.insert( { ...
- 学以致用五----centos7+python3.6.2+django2.1.1
目的,在python 3.6的基础上搭建 django 2.x 一.使用pip安装django ,但是使用pip命令的时候报错,解决方法,做软连接 ln -s /usr/local/python/bi ...
- 关于TM影像各波段组合的简介
321:真彩色合成,即3.2.1波段分别赋予红.绿.蓝色,则获得自然彩色合成图像,图像的色彩与原地区或景物的实际色彩一致,适合于非遥感应用专业人员使用. 432:标准假彩色合成,即4.3.2波段分别赋 ...
- 19) maven 项目结构:聚集
Project Aggregation [,æɡrɪ'ɡeɪʃən] https://maven.apache.org/guides/introduction/introduction-to-the- ...
- UIActivityIndicatorView 的使用
// // UIActivityIndicator.m // ToolBar // // Created by lanouhn on 15/1/3. // Copyright (c) 2015 ...