神奇的restful规范
这里直接引用百度的解释什么是restful
建立restfulAPI模块
这个模块的作用主要是做一些前置操作和指引,并且规范路径,同时对错误进行初步处理
app_need/restfulAPI.js
'use strict';
module.exports = {
APIError: function (code, message) {//编辑数据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)) {
// 绑定rest()方法:
ctx.rest = (data) => {
ctx.response.status = 200;
ctx.response.type = 'application/json';
ctx.response.body = data;
}
try {
//正常情况是上面的绑定ctx
await next();
} catch (e) {
// 非正常情况下是下面的绑定ctx
ctx.response.status = 400;
ctx.response.type = 'application/json';
ctx.response.body = {
code: e.code || 'internal:unknown_error',
message: e.message || ''
};
}
} else {
await next();
}
};
}
};
在app.js引用
app.js
const rest=require('./app_need/restfulAPI');
app.use(rest.restify('/api'));//使用中间件写法,并且声明api接口的路径
编写api路由
routes/api_user.js
'use strict';
const router = require('koa-router')();
router.prefix('/api/user');
router.get('/:id', function (ctx, next) {//定义读取
console.log(ctx.params.id);
ctx.rest({ data: 'api_user接口接口get' });
});
router.post('/:id', function (ctx, next) {//定义增加
console.log(ctx.params.id);
ctx.rest({ data: 'api_user接口接口post' });
});
router.put('/:id', function (ctx, next) {//定义更新
console.log(ctx.params.id);
ctx.rest({ data: 'api_user接口接口put' });
});
router.del('/:id', function (ctx, next) {//定义删除
console.log(ctx.params.id);
ctx.rest({ data: 'api_user接口接口del' });
});
router.patch('/:id', function (ctx, next) {//定义局部更新
console.log(ctx.params.id);
ctx.rest({ data: 'api_user接口接口patch' });
});
module.exports = router;
最终项目地址:https://github.com/jijuxie/koa2_all.git