node.js项目改进之restful API接口支持
来源:互联网 发布:道路车流量预测软件 编辑:程序博客网 时间:2024/05/17 22:50
神奇的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 0
- node.js项目改进之restful API接口支持
- Node.js RESTful API
- Node.js RESTful API
- Node.js RESTful API
- Node.js RESTful API
- Node.js RESTful API
- node.js项目改进之环境配置
- node.js项目改进之日志系统
- node.js项目改进之分离控制器
- node.js项目改进之View模块改进
- node.js项目改进之改进mysql模块(2)
- Node.js与Restful API
- 浅谈node.js RESTful API
- IT前沿技术之node.js篇<四>:Node.js与Restful API
- node.js项目改进之更新重启nodemon
- node.js项目改进之路由分发系统
- 使用Node.js + MongoDB 构建restful API
- Node.js - RESTful API - web service
- phpqrcode 生成二维码
- Linux达人养成计划一
- try_to_wake_up函数
- VirtualBox中的Mac系统的使用心得
- python3 实现自动生成入账记录表
- node.js项目改进之restful API接口支持
- hdu 2016
- 不规则时间字符串处理(Java)
- Golang集成环境与HelloWorld
- SecureCRT SSH自动化采集脚本
- Netty5的例子,简单介绍Netty的用法
- maven安装本地jar包
- 【JAVA秒会技术之玩转图片】图片下载和等比或指定大小压缩快速实现
- 一款轻量级写作神器Typora