本文转自: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. The SQL Server instance returned an invalid or unsupported protocol version during login negotiatio

    在使用.net core 连接sqlserver的时候遇到了这个问题 从字面意思理解大致是个什么版本不支持, 谷歌一下吧,ok,看到这个2000我就知道什么问题了 我的数据库还是2000的,总算把20 ...

  2. RCNN论文细节

    写在前面: 本系列笔记主要记录本人在阅读过程中的收获,尽量详细到实现层次,水平有限,欢迎留言指出问题~ 这篇文章被认为是深度学习应用于目标检测的开山之作,自然是要好好读一下的,由于文章是前些日子读的, ...

  3. vue中计算属性computed方法内传参

    vue中computed计算属性无法直接进行传参 如果有传参数的需求比如说做数据筛选功能可以使用闭包函数(也叫匿名函数)实现 例如: 在上篇博客vue安装使用最后的成绩表练习中的过滤功能的实现: &l ...

  4. ARouter基础使用(一)

    一个用于帮助 Android App 进行组件化改造的框架 —— 支持模块间的路由.通信.解耦1.新建一个Android项目 "ARouterDemo"2.添加依赖和配置 andr ...

  5. 浅谈开发中python通过os模块存储数据

    #其实本人很烦发博客,但为了面试还是发一下好,证明一下自己的能力 前言 首先说一下适用环境,在开发中我们有一些经常用到的数据(数据量大)需要存储起来. 存sql嘛又不合适,要知道在开发中每条sql语句 ...

  6. Vs 开发时无法断点问题

    1.清除解决方案 2.重新编译 3.删除项目目录下的obj 和 bin 4.在vs中配置 工具--项目--调试--去除勾选 要求源文件与原始版本完全匹配 关于调试问题 1.关闭诊断工具, 工具 =&g ...

  7. 【RL-TCPnet网络教程】第20章 RL-TCPnet之BSD Socket客户端

    第20章      RL-TCPnet之BSD Socket客户端 本章节为大家讲解RL-TCPnet的BSD Socket,学习本章节前,务必要优先学习第18章的Socket基础知识.有了这些基础知 ...

  8. [Swift]LeetCode269. 外星人词典 $ Alien Dictionary

    There is a new alien language which uses the latin alphabet. However, the order among letters are un ...

  9. [Swift]LeetCode991. 坏了的计算器 | Broken Calculator

    On a broken calculator that has a number showing on its display, we can perform two operations: Doub ...

  10. Identity Server 4 中文文档(v1.0.0) 目录

    欢迎来到IdentityServer4 第一部分 简介 第1章 背景 第2章 术语 第3章 支持和规范 第4章 打包和构建 第5章 支持和咨询选项 第6章 演示服务器和测试 第7章 贡献 第二部分 快 ...