node.js使用restify開發REST web services

BeaLoftin 8年前發布 | 26K 次閱讀 數據庫 Node.js Web服務 Node.js 開發

來自: 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
  }
]

e???e???完成了今天的任務了。

總結

我們初步學會了創建 REST API 服務,在 node.js 中連接 mysql 以及 sql 的使用。但是這樣的代碼還有很多需要改進的地方,這是我們下一步要做的。

更多內容可以關注我

微博

Github

 本文由用戶 BeaLoftin 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!