好好学习,天天向上

Nothing is impossible to a willing heart.

热爱前端,编程使我快乐 | 邮箱:summerlisi@163.com

一个简单的使用restc demo

最近不经意间看到饿了么团队开发的restc,接口调试工具(类似postman),其实调试接口都没用过工具,每次都只是运行起项目直接调接口。闲来无事,看到restc,就决定试试,后面觉得挺不错的,就分享一下。

第一步:搭建小框架

打开终端执行命令:

  1. mkdir restc-demo
  2. cd restc-demo
  3. npm init -y

这样一个小小的框架就出来了。

第二步:新建json文件

在项目的根目录下新建两个json文件,用来模拟后台接口;
接口返回结果类似:

[ { "activities":[ { "description": "在线支付满25减11,满50减15,满75减201233333444", "icon_color": "f07373323323", "icon_name": "减23455", "id": 15356977234, "name": "满减优惠123" } ] } ]

第三步:修改package.json文件

这个文件在我们npm init的时候已经生成

这时我们直接在这里添加好我们需要用到的包,然后npm install 一下就会自动安装这里面的包了;

{ "name": "restc-demo", "version": "1.0.0", "description": "An example to demostrate how to use restc in koa 1.x.", "main": "index.js", "keywords": [], "author": "summer", "license": "ISC", "dependencies": { "koa": "^1.2.4", "koa-static": "^2.0.0", "restc": "0.0.4" } }

第四步:安装 mount

一般我们的项目都比较大,在这种情况下我们是不希望我们页面也变成像接口请求一样,我们肯定希望页面正常显示,只是我们在输入接口的时候跳到我们引入的restc UI进行查看接口状态,这时我们就需要用到 koa-mount模块来挂载。

执行命令:npm install koa-mount

第五步:编辑index.js文件

代码如下:

const mount = require('koa-mount'); //引入挂载模块

const serve = require('koa-static'); //静态服务器,访问我们新建好的json模拟文件

const koa = require('koa');

const restc = require('restc'); //引入调试接口模块

// for express

// app.use(restc.express());

// for koa

var a = koa();

a.use(restc.koa());

a.use(serve('.'));

// ...and koa2

// app.use(restc.koa2());

var b = koa();

b.use(function *(next) { yield next; this.body = { message: 'Hello world!'}; });

var app = koa();

app.use(mount('/hello', a)); // 运行时访问 localhost:3000/hello/test1.json 就能访问到我们新建的json文件

app.use(mount('/world', b)); //运行时访问 localhost:3000/world 就能看到上面的 Hello world 页面

app.listen(3000);}

最后 node index.js 运行项目就可以了

来源:https://elemefe.github.io/restc/guide/###

posted @ 2017-01-12 16:22  文思旋风  阅读(386)  评论(0编辑  收藏  举报