本文转自: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的更多相关文章

  1. web全栈后台权限管理系统(VUE+ElementUi+nodeJs+koa2)

    web全栈后台权限管理系统(VUE+ElementUi+nodeJs+koa2) 主要技术 前端 vue 全家桶 ElementUI 后端 Node.js Koa2 Mongoess 数据库 mong ...

  2. vuejs目录结构启动项目安装nodejs命令,api配置信息思维导图版

    vuejs目录结构启动项目安装nodejs命令,api配置信息思维导图版 vuejs技术交流QQ群:458915921 有兴趣的可以加入 vuejs 目录结构 build build.js check ...

  3. 把 nodejs koa2 制作的后台接口 部署到 腾讯云服务器

    我 使用 nodejs koa2框架 制作后端接口, 现在将nodejs koa2 部署到服务器 koa2项目 实现 接口 可以看我的 这篇文章: 简单实现 nodejs koa2 mysql 增删改 ...

  4. 简单实现 nodejs koa2 mysql 增删改查 制作接口

    1.首先 在电脑上安装 nodejs (此处略过) 2.全局安装 koa2 (这里使用的淘宝镜像cnpm,有兴趣的同学可以自行搜索下) cnpm install koa-generator -g 3. ...

  5. nodejs:express API之res.locals

    在从零开始nodejs系列文章中,有一个login.html文件 再来看它的get方法,我们并没有看到mess字段.那mess到底是从哪里来的呢? 接着我看到app.js文件里面: 只有这里出现了me ...

  6. Node与apidoc的邂逅——NodeJS Restful 的API文档生成

    作为后台根据需求文档开发完成接口后,交付给前台(angular vue等)做开发,不可能让前台每个接口调用都去查看你的后台代码一点点查找.前台开发若不懂你的代码呢?让他一个接口一个接口去问你怎么调用, ...

  7. nodejs的某些api~(五) HTTP模块

    HTTP的模块是nodejs最重要的模块(应该是),最近在看HTTP权威指南,重新过了一遍http协议和web客户端.再来看这个http. HTTP构建于TCP之上,属于应用层协议,继承自tcp服务器 ...

  8. nodejs的某些api~(一)node的流1

    根据心情整理一些node的api~ 今天第一篇,node的流:node的流比较重要,node的流存在于node的各个模块,包括输入输出流,stdin,stout.fs读取流,zlib流,crypto流 ...

  9. NodeJs学习之API篇

    学习nodeJS的API在对于使用nodeJS来进行编程的是十分重要的,所以首先就要去学习看看,相关的node的模块,来看一看相关的内容和可用性. 正文篇: nodeJS的API学习之路.(这里我们将 ...

  10. nodejs利用windows API读取文件属性(dll)

    nodejs调用delphi编写的dll中,使用了dll调用windows api转读取文件属性,感觉使用nodejs也可直接调用windows api. 此处需用到windows系统的version ...

随机推荐

  1. 关于在centos7 64为引用android so引发的问题修复

    背景: 公司有解码的app,解码库位c++编写so动态库. 之前做过一版在调用html5摄像头,然后提取图像进行解码,后面因为图像质量不佳放弃. 最近 因为小程序api有更新 可以获取到相对清晰的图像 ...

  2. kvm虚拟机克隆

    1.先关闭被克隆的虚拟机: 2.克隆命令 virt-clone -o 192.168.0.242_sw_web -n 192.168.0.163_nginx -f /data/kvm/images/1 ...

  3. python语法_列表生成器_生成器_迭代器_异常捕获

    列表生成式 a = [x for x in range(10)] print(a) x 可进行操作 a = [x*2 for x in range(10)] print(a) x甚至可以为函数, de ...

  4. Egret 生成 自带EUI 的微信小游戏 踩坑!

    1. 首先,再次被网上一大堆屎一样的资料搞得浪费了我一天时间.各种坑. 2. 本文先讲一种正确的方式,然后再列举坑. 去www.egret.com下载最新的引擎,我的最新版本是5.2.2. 然后就会被 ...

  5. [Swift]LeetCode140. 单词拆分 II | Word Break II

    Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add space ...

  6. [Swift]LeetCode249.群组偏移字符串 $ Group Shifted Strings

    Given a string, we can "shift" each of its letter to its successive letter, for example: & ...

  7. [Swift]LeetCode966.元音拼写检查器 | Vowel Spellchecker

    Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word ...

  8. [Swift]LeetCode994. 腐烂的橘子 | Rotting Oranges

    In a given grid, each cell can have one of three values: the value 0 representing an empty cell; the ...

  9. [Swift]LeetCode1028. 从先序遍历还原二叉树 | Recover a Tree From Preorder Traversal

    We run a preorder depth first search on the root of a binary tree. At each node in this traversal, w ...

  10. CoCos2dx开发:更换导出的app名称和图标

    要处理的文件路径如下: 1.更换图标: drawable-hdpi.drawable-ldpi.drawable-mdpi三个文件夹分别代表大.小.中三个不同宽高的图片,为了应对手机的不同分辨率,来采 ...