node-restify简介

restifyNode.js的模块。虽然restify的API或多或少的参考了express,但restify不是一个MVC框架,它是一套为了能够正确构建REST风格API而诞生的框架。

###安装restify

restify安装到目录restify-dmeo

$ mkdir restify-demo
$ cd restify-demo $ npm install restify

###Hello World

var restify = require('restify'); function respond(req, res, next) { res.send('hello ' + req.params.name); } var server = restify.createServer(); server.get('/hello/:name', respond); server.listen(8080, function() { console.log('%s listening at %s', server.name, server.url); });

保存文件并执行

$ node app.js
restify listening at http://0.0.0.0:8080

通过curl命令测试,服务器返回HTTP状态码200和一个application/json类型的内容(事实上这里不是)

$ curl -is http://localhost:8080/hello/roy HTTP/1.1 200 OK Access-Control-Allow-Origin: * Access-Control-Allow-Headers: Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version Access-Control-Expose-Headers: X-Api-Version, X-Request-Id, X-Response-Time Server: restify X-Request-Id: ec3e9e55-7083-4e12-93ee-9c24a0c5c398 Access-Control-Allow-Methods: GET Connection: close Content-Length: 5 Content-MD5: 65tW24XBT3r1jLUpw0o0Fw== Content-Type: application/json Date: Sun, 19 Feb 2012 16:14:13 GMT X-Response-Time: 3 "hello roy"

###特性 接触到restify是因为内部系统需要一个手机归属地的查询接口,基于nodejsredis的高性能实现,决定快速实现一个,当时也很自然地选择了express作为web层。但express始终是一个Web MVC框架,它包含了一些我不太需要的功能实现(i.e., templating/rendering)。而我只是需要一个更纯粹的API接口而已–接收请求然后返回一个JSON结果集。

后来从推上找到了restify时,我就觉得这才是我想要的:

  1. 路由

    • 基本等同于express/sinatra的路由方式
    • 路由正则表达式支持
    • 版本化支持
  2. 自动选择内容格式进行响应,并可以自定义格式

  3. 内置REST风格的错误处理机制,重载了400和409来解析应答,得到一个包含codemessage的JSON对象。也可以子类化restify.RestError实现自己错误代码和信息。

    已实现的RestError:

    • RestError
    • BadDigestError
    • BadMethodError
    • InternalErrorError
    • InvalidArgumentError
    • InvalidContentError
    • InvalidCredentialsError
    • InvalidHeaderError
    • InvalidVersionError
    • MissingParameterError
    • NotAuthorizedError
    • RequestExpiredError
    • RequestThrottledError
    • ResourceNotFoundError
    • WrongAcceptError
  4. 插件机制

  5. DTrace支持,这个绝对是调式、诊断和性能测量利器

虽然现在restify还是初生婴儿,我还是把上面提到的手机归属地查询接口改用了restify来实现了一个moquery

正如官方描述一样

restify is a smallish framework, similar to `express` for building REST APIs.

转载于:https://www.cnblogs.com/dyg540/p/4754674.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值