[转]nodeJs--koa2 REST API
本文转自:https://blog.csdn.net/davidPan1234/article/details/83413958
REST API规范
编写REST API,实际上就是编写处理HTTP请求的async函数,不过,REST请求和普通的HTTP请求有几个特殊的地方:
REST请求仍然是标准的HTTP请求,但是,除了GET请求外,POST、PUT等请求的body是JSON数据格式,请求的Content-Type为application/json;
REST响应返回的结果是JSON数据格式,因此,响应的Content-Type也是application/json。
1、工程结构
2、目录详解
package.json:项目描叙
{
"name": "rest-koa",
"version": "1.0.0",
"description": "rest-koa project",
"main": "app.js",
"scripts": {
"dev": "node --use_strict app.js"
},
"keywords": [
"koa",
"rest",
"api"
],
"author": "david pan",
"dependencies": {
"koa": "2.0.0",
"koa-bodyparser": "3.2.0",
"koa-router": "7.0.0"
}
}
app.js
const Koa = require('koa');
const app = new Koa();
const bodyParser = require('koa-bodyparser');
const controller = require('./controller');
const rest = require('./rest');
// parse request body:
app.use(bodyParser());
// bind .rest() for ctx:
app.use(rest.restify());
// add controller:
app.use(controller());
app.listen(3000);
console.log('app started at port 3000...');
(1). controller.js--- 路由集中处理
const fs = require('fs');
// add url-route in /controllers:
function addMapping(router, mapping) {
for (var url in mapping) {
if (url.startsWith('GET ')) {
var path = url.substring(4);
router.get(path, mapping[url]);
console.log(`register URL mapping: GET ${path}`);
} else if (url.startsWith('POST ')) {
var path = url.substring(5);
router.post(path, mapping[url]);
console.log(`register URL mapping: POST ${path}`);
} else if (url.startsWith('PUT ')) {
var path = url.substring(4);
router.put(path, mapping[url]);
console.log(`register URL mapping: PUT ${path}`);
} else if (url.startsWith('DELETE ')) {
var path = url.substring(7);
router.del(path, mapping[url]);
console.log(`register URL mapping: DELETE ${path}`);
} else {
console.log(`invalid URL: ${url}`);
}
}
}
function addControllers(router, dir) {
fs.readdirSync(__dirname + '/' + dir).filter((f) => {
return f.endsWith('.js');
}).forEach((f) => {
console.log(`process controller: ${f}...`);
let mapping = require(__dirname + '/' + dir + '/' + f);
addMapping(router, mapping);
});
}
module.exports = function (dir) {
let
controllers_dir = dir || 'controllers',
router = require('koa-router')();
addControllers(router, controllers_dir);
return router.routes();
};
(2). rest.js--- 支持rest的中间件middleware
a.定义错误码的统一处理
b.统一输出REST
如果每个异步函数都编写下面这样的代码:
// 设置Content-Type:
ctx.response.type = 'application/json';
// 设置Response Body:
ctx.response.body = {
products: products
};
很显然,这样的重复代码很容易导致错误,例如,写错了字符串'application/json',或者漏写了ctx.response.type = 'application/json',都会导致浏览器得不到JSON数据。
写这个中间件给ctx添加一个rest()方法,直接输出JSON数据
module.exports = {
APIError: function (code, message) {
this.code = code || 'internal:unknown_error';
this.message = message || '';
},
restify: (pathPrefix) => {
pathPrefix = pathPrefix || '/api/';
return async (ctx, next) => {
if (ctx.request.path.startsWith(pathPrefix)) {
console.log(`Process API ${ctx.request.method} ${ctx.request.url}...`);
ctx.rest = (data) => {
ctx.response.type = 'application/json';
ctx.response.body = data;
}
try {
await next();
} catch (e) {
console.log('Process API error...');
ctx.response.status = 400;
ctx.response.type = 'application/json';
ctx.response.body = {
code: e.code || 'internal:unknown_error',
message: e.message || ''
};
}
} else {
await next();
}
};
}
};
(3). controllers/api.js--- rest api的定义
具体的api定义,这里可以优化下:不同模块建立文件夹,如products/Api.js, car/api.js ...这样更清晰
const products = require('../model/products');
const APIError = require('../rest').APIError;
module.exports = {
'GET /api/products': async (ctx, next) => {
ctx.rest({
products: products.getProducts()
});
},
'POST /api/products': async (ctx, next) => {
var p = products.createProduct(ctx.request.body.name, ctx.request.body.manufacturer, parseFloat(ctx.request.body.price));
ctx.rest(p);
},
'DELETE /api/products/:id': async (ctx, next) => {
console.log(`delete product ${ctx.params.id}...`);
var p = products.deleteProduct(ctx.params.id);
if (p) {
ctx.rest(p);
} else {
throw new APIError('400', 'product not found by id.');
}
}
};
(4). model/products.js--- 具体的model逻辑处理
模拟数据库操作
// store products as database:
var id = 0;
function nextId() {
id++;
return 'p' + id;
}
function Product(name, manufacturer, price) {
this.id = nextId();
this.name = name;
this.manufacturer = manufacturer;
this.price = price;
}
var products = [
new Product('iPhone 7', 'Apple', 6800),
new Product('ThinkPad T440', 'Lenovo', 5999),
new Product('LBP2900', 'Canon', 1099)
];
module.exports = {
getProducts: () => {
return products;
},
getProduct: (id) => {
var i;
for (i = 0; i < products.length; i++) {
if (products[i].id === id) {
return products[i];
}
}
return null;
},
createProduct: (name, manufacturer, price) => {
var p = new Product(name, manufacturer, price);
products.push(p);
return p;
},
deleteProduct: (id) => {
var
index = -1,
i;
for (i = 0; i < products.length; i++) {
if (products[i].id === id) {
index = i;
break;
}
}
if (index >= 0) {
// remove products[index]:
return products.splice(index, 1)[0];
}
return null;
}
};
3、postman调试
npm run dev
postman测试增、查、删
---------------------
作者:空谷足音 -จุ
来源:CSDN
原文:https://blog.csdn.net/davidPan1234/article/details/83413958
版权声明:本文为博主原创文章,转载请附上博文链接!
[转]nodeJs--koa2 REST API的更多相关文章
- web全栈后台权限管理系统(VUE+ElementUi+nodeJs+koa2)
web全栈后台权限管理系统(VUE+ElementUi+nodeJs+koa2) 主要技术 前端 vue 全家桶 ElementUI 后端 Node.js Koa2 Mongoess 数据库 mong ...
- vuejs目录结构启动项目安装nodejs命令,api配置信息思维导图版
vuejs目录结构启动项目安装nodejs命令,api配置信息思维导图版 vuejs技术交流QQ群:458915921 有兴趣的可以加入 vuejs 目录结构 build build.js check ...
- 把 nodejs koa2 制作的后台接口 部署到 腾讯云服务器
我 使用 nodejs koa2框架 制作后端接口, 现在将nodejs koa2 部署到服务器 koa2项目 实现 接口 可以看我的 这篇文章: 简单实现 nodejs koa2 mysql 增删改 ...
- 简单实现 nodejs koa2 mysql 增删改查 制作接口
1.首先 在电脑上安装 nodejs (此处略过) 2.全局安装 koa2 (这里使用的淘宝镜像cnpm,有兴趣的同学可以自行搜索下) cnpm install koa-generator -g 3. ...
- nodejs:express API之res.locals
在从零开始nodejs系列文章中,有一个login.html文件 再来看它的get方法,我们并没有看到mess字段.那mess到底是从哪里来的呢? 接着我看到app.js文件里面: 只有这里出现了me ...
- Node与apidoc的邂逅——NodeJS Restful 的API文档生成
作为后台根据需求文档开发完成接口后,交付给前台(angular vue等)做开发,不可能让前台每个接口调用都去查看你的后台代码一点点查找.前台开发若不懂你的代码呢?让他一个接口一个接口去问你怎么调用, ...
- nodejs的某些api~(五) HTTP模块
HTTP的模块是nodejs最重要的模块(应该是),最近在看HTTP权威指南,重新过了一遍http协议和web客户端.再来看这个http. HTTP构建于TCP之上,属于应用层协议,继承自tcp服务器 ...
- nodejs的某些api~(一)node的流1
根据心情整理一些node的api~ 今天第一篇,node的流:node的流比较重要,node的流存在于node的各个模块,包括输入输出流,stdin,stout.fs读取流,zlib流,crypto流 ...
- NodeJs学习之API篇
学习nodeJS的API在对于使用nodeJS来进行编程的是十分重要的,所以首先就要去学习看看,相关的node的模块,来看一看相关的内容和可用性. 正文篇: nodeJS的API学习之路.(这里我们将 ...
- nodejs利用windows API读取文件属性(dll)
nodejs调用delphi编写的dll中,使用了dll调用windows api转读取文件属性,感觉使用nodejs也可直接调用windows api. 此处需用到windows系统的version ...
随机推荐
- Scanner,Random,匿名对象-------------------java基础学习第七天
1.API 2.Scanner 功能:通过键盘输入数据到程序中. 引用类型的一般使用步骤: 导包 Import 包路径.类名称 只有java.lang 包写的类不需要导包,其他都需要 2.创建 类名称 ...
- curl命令行请求
curl -H "Content-Type: application/json" -X POST --data 'json post数据' -i http://xxx
- Hadoop集群搭建-full完全分布式(三)
环境:Hadoop-2.8.5 .centos7.jdk1.8 一.步骤 1).4台centos虚拟机 2). 将hadoop配置修改为完全分布式 3). 启动完全分布式集群 4). 在完全分布式集群 ...
- 关于如何在Visual Studio上仿真调试安卓的U3D应用
正巧最近需要开发一个安卓手机上的Unity3D游戏功能,想着既然要开发么,当然需要调试.本来的话一些基础功能是不需要使用仿真模拟器,直接在U3D的开发编辑器上就能调试,不过有一些安卓上才能执行,比如 ...
- es5中的for in 与es6中的for of的用法与区别
for in 用与循环遍历对象中的属性键值 for of用于循环遍历出数组中的属性值 for in 也可以遍历数组,但是局限是他会把数组的其他属性键值也会遍历出,例如给数组添加一个属性arr.name ...
- 电子科技大学实验中学PK赛(三)-期末测试比赛题解
比赛地址:http://qscoj.cn/contest/33/ A题 国家德比 分析:用b,d,B,D记录两场比赛两支球队的比分,先判断b+B与d+D的大小,如果先者大则拜仁胜,后者大则多特胜:相同 ...
- json格式 (JavaScipt Object Notation)
json格式 json语法规则: 01.对象表现形式 key:value 键值对 02.如果有多个数据,之间使用逗号隔开 k1:v1,k2:v2 03.把对象写在大括号中 var student={a ...
- VUE插件大总结
UI组件 element - 饿了么出品的Vue2的web UI工具套件 Vux - 基于Vue和WeUI的组件库 mint-ui - Vue 2的移动UI元素 iview - 基于 Vuejs 的开 ...
- 【安富莱二代示波器教程】第16章 附件A---电阻屏触摸校准
第16章 附件A---电阻屏触摸校准 二代示波器的触摸校准比较简单,随时随地都可以做触摸校准,按下K1按键即可校准.有时候我们做触摸校准界面,需要在特定的界面才可以进入触摸校准状态,非常繁琐 ...
- ubuntu系统界面改变
主题:https://gitzab.com/Anduin/GNOME-OSX-II-Theme.git图标:https://github.com/keeferrourke/la-capitaine-i ...