node.js使用restify开发REST web services
BeaLoftin
9年前
来自: http://itjhdev.github.io/2016/02/22/nodejs-restify-restapi-mysql/
文章主要包括restify开发api,node.js连接mysql返回json数据等。
restify简介
restify 是一个基于Nodejs的REST应用框架,支持服务器端和客户端。 restify 比起 express 更专注于 REST 服务,去掉了 express 中的 template , render 等功能,同时强化了 REST 协议使用,版本化支持, HTTP 的异常处理。
Github: node-restify
API: API DOCUMENTATION
restify安装
- 新建项目
mkdir nodejs_restify cd nodejs_restify npm install restify
出现以下内容表示安装成功
restify@4.0.4 ../../../../node_modules/restify ├── assert-plus@0.1.5 ├── tunnel-agent@0.4.2 ├── escape-regexp-component@1.0.2 ├── keep-alive-agent@0.0.1 ├── negotiator@0.5.3 ├── mime@1.3.4 ├── lru-cache@2.7.3 ├── formidable@1.0.17 ├── node-uuid@1.4.7 ├── qs@3.1.0 ├── semver@4.3.6 ├── spdy@1.32.5 ├── once@1.3.3 (wrappy@1.0.1) ├── http-signature@0.11.0 (ctype@0.5.3, asn1@0.1.11) ├── verror@1.6.1 (core-util-is@1.0.2, extsprintf@1.2.0) ├── vasync@1.6.3 (verror@1.6.0) ├── backoff@2.4.1 (precond@0.2.3) ├── csv@0.4.6 (csv-generate@0.0.6, csv-stringify@0.0.8, stream-transform@0.1.1, csv-parse@1.0.1) ├── bunyan@1.7.0 (safe-json-stringify@1.0.3, moment@2.11.2, mv@2.1.1) └── dtrace-provider@0.6.0 (nan@2.2.0)
- 创建rest服务
touch app.js
- app.js内容
var restify = require('restify'); function respond(req, res, next) { res.send('hello ' + req.params.name); next(); } var server = restify.createServer({ name: 'ds_api', version: '1.0.0' }); server.get('/hello/:name', respond); server.head('/hello/:name', respond); server.listen(8081, function() { console.log('%s listening at %s', server.name, server.url); });
- 启动服务
node app.js listening at http://[::]:8081
- 使用 curl 测试
curl -is http://localhost:8081/hello/mark HTTP/1.1 200 OK Content-Type: application/json Content-Length: 12 Date: Mon, 22 Feb 2016 06:57:42 GMT Connection: keep-alive "hello mark"
OK,我们创建了一个8080端口的rest服务,包括 /hello/:name 接口.
更多内容可以访问 API DOCUMENTATION
Mysql服务
- 安装mysql
npm install felixge/node-mysql
- 在 app.js 创建服务
// 连接mysql var mysql = require('mysql'); var conn = mysql.createConnection({ host: ‘ip’, user: ‘user’, password: ‘pasw’, database:'ds_video', port: 3306 });
- 重写 逗视 获取视频的接口
server.get('queryListVideo/:vid/:count/:type/:userId',function respond(req, res, next) { conn.query( { sql: 'select distinct v.title as title,v.id,v.url as videoUrl ,v.pic,v.type,v.createTime as pushTime ,'+ '(select count(*) from `tb_user_video` tub WHERE tub.`status` = 1 AND tub.userId = ? AND tub.videoId = v.id) as isCollectStatus'+ ' from `tb_video` v where'+ ' v.title != "" AND v.title not like "%#%" AND v.title not like "%@%" AND v.title not like "%微%" '+ ' AND v.title not like "%秒拍%" AND v.title not like "%号%" '+ ' AND v.title not like "%美拍%" '+ ' AND type = ? '+ 'ORDER BY id DESC LIMIT ?' , values: [req.params.userId,req.params.type,parseInt(req.params.count)] }, function(err, rows, fields) { if (err) throw err; console.log('The title is: ', title = rows[0].title); res.send(200, res.json(rows)); }); return next(); });
创建了 queryListVideo 服务, /:vid/:count/:type/:userId 参数,
:vid 格式传递参数,
req.params.vid 获取参数值
res.json(rows) 数据json格式输出
res.send(200, res.json(rows)); 服务返回值 200 HTTP状态码, res.json(rows) 数据
conn.query( { sql: ’sql语句 ?’, values: [] // ? 填充值 }, function(err, rows, fields) { //数据库返回数据 if (err) throw err; res.send(200, res.json(rows)); });
OK,我们测试一下吧!
服务地址: http://127.0.0.1:8081/queryListVideo/0/10/2/1
返回内容:
[ { "title": "我也是醉了", "id": 37729, "videoUrl": "http://mvvideo2.meitudata.com/56c8a0c08e10d5457.mp4", "pic": "http://mvimg1.meitudata.com/56c8a0bfef7c11168.jpg!thumb320", "type": 2, "pushTime": "2016-02-20T18:11:33.000Z", "isCollectStatus": 0 }, { "title": "女神如此难追", "id": 37727, "videoUrl": "http://mvvideo2.meitudata.com/56c7de946f8bb3420.mp4", "pic": "http://mvimg11.meitudata.com/56c8150c4fe9d9762.jpg!thumb320", "type": 2, "pushTime": "2016-02-20T18:11:32.000Z", "isCollectStatus": 0 }, { "title": "一个疯子+一个傻子=两张大饼脸️精彩活动️问:视频中我说了几个啥玩意儿完全即兴某人还不知道规则", "id": 37726, "videoUrl": "http://mvvideo1.meitudata.com/56c8a0186f59d9869.mp4", "pic": "http://mvimg2.meitudata.com/56c8a10eaa5394719.jpg!thumb320", "type": 2, "pushTime": "2016-02-20T18:11:32.000Z", "isCollectStatus": 0 }, { "title": "爆笑歌词梗", "id": 37704, "videoUrl": "http://mvvideo1.meitudata.com/56c0438416f2a3712.mp4", "pic": "http://mvimg10.meitudata.com/56c832793e9705833.jpg!thumb320", "type": 2, "pushTime": "2016-02-20T17:14:14.000Z", "isCollectStatus": 0 }, { "title": "情感专线-拜金女的那些事儿", "id": 37701, "videoUrl": "http://gslb.miaopai.com/stream/Lqn~dQ1tbuJ5KNkc~LAG1A__.m3u8", "pic": "http://wsacdn3.miaopai.com/stream/Lqn~dQ1tbuJ5KNkc~LAG1A___m.jpg", "type": 2, "pushTime": "2016-02-20T17:14:13.000Z", "isCollectStatus": 0 }, { "title": "一网友说她家鹦鹉笑起来好像她奶奶[笑cry]", "id": 37696, "videoUrl": "http://gslb.miaopai.com/stream/59hdWRg61qsMMwvT5BXPNg__.mp4?vend=miaopai&59hdWRg61qsMMwvT5BXPNg__.mp4miaopai", "pic": "http://wsacdn1.miaopai.com/stream/59hdWRg61qsMMwvT5BXPNg___tmp_11_363_.png", "type": 2, "pushTime": "2016-02-20T17:14:11.000Z", "isCollectStatus": 0 }, { "title": "捉迷藏1 这当爹的心太大了吧!这不摆明了坑儿子么?!", "id": 37681, "videoUrl": "http://gslb.miaopai.com/stream/fKPmQViX6eytWcD6XxR2Yw__.mp4?vend=miaopai&fKPmQViX6eytWcD6XxR2Yw__.mp4miaopai", "pic": "http://wsqncdn.miaopai.com/stream/fKPmQViX6eytWcD6XxR2Yw___m.jpg", "type": 2, "pushTime": "2016-02-20T16:12:51.000Z", "isCollectStatus": 0 }, { "title": "聚会上最装逼的人", "id": 37664, "videoUrl": "http://mvvideo1.meitudata.com/56c7fbce28caf6036.mp4", "pic": "http://mvimg1.meitudata.com/56c703002a0dc7724.jpg!thumb320", "type": 2, "pushTime": "2016-02-20T15:22:30.000Z", "isCollectStatus": 0 }, { "title": "现在的女生真的很现实", "id": 37659, "videoUrl": "http://mvvideo2.meitudata.com/56c87dd4057812379.mp4", "pic": "http://mvimg2.meitudata.com/56c87ded57b056131.jpg!thumb320", "type": 2, "pushTime": "2016-02-20T15:22:26.000Z", "isCollectStatus": 0 }, { "title": "断奶篇-唱回到过去", "id": 37658, "videoUrl": "http://gslb.miaopai.com/stream/aeNf6EQmnzUo4J22Ms~Tfg__.mp4?vend=miaopai&aeNf6EQmnzUo4J22Ms~Tfg__.mp4miaopai", "pic": "http://wsqncdn.miaopai.com/stream/aeNf6EQmnzUo4J22Ms~Tfg___m.jpg", "type": 2, "pushTime": "2016-02-20T15:22:25.000Z", "isCollectStatus": 0 } ]
ðð完成了今天的任务了。
总结
我们初步学会了创建 REST API 服务,在 node.js 中连接 mysql 以及 sql 的使用。但是这样的代码还有很多需要改进的地方,这是我们下一步要做的。
</div>