本文转自: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. prometheus — nginx-vts-exporter

    参考文档: https://blog.51cto.com/xujpxm/2080146 注: 本文留用自己参考,建议看以上参考文档,更为细致 prometheus 监控 nginx 使用 nginx- ...

  2. Prometheus — Process-exporter进程监控

    由于我们常用的node_exporter并不能覆盖所有监控项,这里我们使用Process-exporter 对进程进行监控. 安装process-exporter wget https://githu ...

  3. linux mysql 安装

    操作系统 Centos 7.2以上版本 操作系统 centos 7.2以上版本 mysql 版本 mysql-5.7.23-el7-x86_64.tar.gz 1.1 安装准备 1.  创建安装文件存 ...

  4. s:if 判断 s:property

    判断<s:property value="XXX"/> 是否是空字符串 则:<s:if  test=" XXX == ''  ">< ...

  5. javaScript Event Loop + NodeJs问题解析

    http://www.ruanyifeng.com/blog/2014/10/event-loop.html https://github.com/ElemeFE/node-interview/tre ...

  6. 简单工厂模式demo

    1. 简单工厂模式 domain的接口 public interface Color{ public void display(); } red public Class Red implements ...

  7. Mesos源码分析(6): Mesos Master的初始化

      Mesos Master的初始化在src/master/master.cpp中     在Mesos Master的log中,是能看到这一行的.   1.初始化role,并设置weight权重   ...

  8. [python] python django web 开发 —— 15分钟送到会用(只能送你到这了)

    1.安装python环境 1.1 安装python包管理器: wget https://bootstrap.pypa.io/get-pip.py sudo python get-pip.py   1. ...

  9. Python科学计算基础包-Numpy

    一.Numpy概念 Numpy(Numerical Python的简称)是Python科学计算的基础包.它提供了以下功能: 快速高效的多维数组对象ndarray. 用于对数组执行元素级计算以及直接对数 ...

  10. Java开发快速上手

    Java开发快速上手 前言 1.我的大学 2.对初学者的建议 3.大牛的三大特点 4.与他人的差距 第一章 了解Java开发语言 前言 基础常识 1.1 什么是Java 1.1.1 跨平台性 1.2 ...