node.js项目改进之restful API接口支持

神奇的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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值