1. 程式人生 > >【個人筆記重點,不作為參考】主題:restify搭建模擬RESTful API

【個人筆記重點,不作為參考】主題:restify搭建模擬RESTful API

問題:

本地測試時,埠不同,涉及跨域。控制檯提示, No 'Access-Control-Allow-Origin' header is present on the requested resource.

解決辦法:(重點為: res.header("Access-Control-Allow-Origin", "*"); /*表示允許任意域*/)

方法1. 所有介面

server.use(
    function crossOrigin(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        return next();
    });

方法2.某一個介面

server.get('/person', function(req, res){
    res.send({user: 'root', password: '123qwe..'});
    res.header("Access-Control-Allow-Origin", "*");
    console.log('Get request from '+req.method);
});

什麼是 RESTful 架構?

具象狀態傳輸(英文:Representational State Transfer,簡稱REST)是Roy Thomas Fielding博士於2000年在他的博士論文 “Architectural Styles and the Design of Network-based Software Architectures” 中提出來的一種全球資訊網軟體架構風格。

目前在三種主流的Web服務實現方案中,因為REST模式與複雜的SOAP和XML-RPC相比更加簡潔,越來越多的web服務開始採用REST風格設計和實現。例如,Amazon.com提供接近REST風格的Web服務執行圖書查詢;雅虎提供的Web服務也是REST風格的。

具體可以閱讀 阮一峰 的日誌 RESTful API 設計指南 ,或是參考 維基百科

什麼是 restify 框架?

restify is a node.js module built specifically to enable you to build correct REST web services. It intentionally borrows heavily from express as that is more or less the de facto API for writing web applications on top of node.js.

restify 是專門幫助你建立正確的 REST Web 服務的 Node.js 模組,它有意地大量借鑑了Express。

安裝使用 restify

安裝

$ npm install restify

編寫基於 REST 的 API

  1. 新建一個app.js檔案

    $ touch app.js
    
  2. 引入 restify 模組

    var restify = require('restify');
  3. 建立服務

    var server = restify.createServer();
  4. 配置 restify 的外掛

    123 server.use(restify.acceptParser(server.acceptable));server.use(restify.queryParser());server.use(restify.bodyParser());
    • Accept Parser

      Parses out the Accept header, and ensures that the server can respond to what the client asked for. You almost always want to just pass in server.acceptable here, as that’s an array of content types the server knows how to respond to (with the formatters you’ve registered). If the request is for a non-handled type, this plugin will return an error of 406.

      解析 Accept 頭部,確保伺服器可以響應客戶端的請求。一般來說,你只需要傳遞 server.acceptable ,這是一個包含所有伺服器知道如何響應的內容型別的陣列。如果請求一個未知型別,該外掛會返回一個406 錯誤。

    • QueryParser

      Parses the HTTP query string (i.e., /foo?id=bar&name=mark). If you use this, the parsed content will always be available in req.query, additionally params are merged into req.params. You can disable by passing in mapParams: false in the options object:

      解析 HTTP 傳遞的查詢字串(如,/foo?id=bar&name=mark )如果你使用這個外掛,被處理的內容可以通過 req.query 訪問,同時引數會被合併到req.params 中。你可以通過傳遞引數物件{mapParams: false} 來禁用它。

      當不傳入引數時,請求返回的資料如圖:

      無引數情況

      當傳入引數 {mapParams: false} 時,請求返回的資料如圖,可以發現,params 中已經不再帶有引數:

      無引數情況

    • BodyParser

      Blocks your chain on reading and parsing the HTTP request body. Switches on Content-Type and does the appropriate logic. application/json,application/x-www-form-urlencoded andmultipart/form-data are currently supported.

      在讀取和解析 HTTP 請求 body 的時候,改變 Content-Type 並執行相應的邏輯。支援 application/json,application/x-www-form-urlencodedmultipart/form-data 型別。

      Options:

      • maxBodySize - The maximum size in bytes allowed in the HTTP body. Useful for limiting clients from hogging server memory.
      • mapParams - if req.params should be filled with parsed parameters from HTTP body.
      • mapFiles - if req.params should be filled with the contents of files sent through a multipart request. formidable is used internally for parsing, and a file is denoted as a multipart part with thefilename option set in its Content-Disposition. This will only be performed ifmapParams is true.
      • overrideParams - if an entry in req.params should be overwritten by the value in the body if the names are the same. For instance, if you have the route/:someval, and someone posts anx-www-form-urlencoded Content-Type with the bodysomeval=happy to/sad, the value will behappy ifoverrideParams istrue, sad otherwise.
      • multipartHandler - a callback to handle any multipart part which is not a file. If this is omitted, the default handler is invoked which may or may not map the parts intoreq.params, depending on themapParams-option.
      • multipartFileHandler - a callback to handle any multipart file. It will be a file if the part have aContent-Disposition with thefilename parameter set. This typically happens when a browser sends a from and there is a parameter similar to<input type="file" />. If this is not provided, the default behaviour is to map the contents intoreq.params.
      • keepExtensions - if you want the uploaded files to include the extensions of the original files (multipart uploads only). Does nothing ifmultipartFileHandler is defined.
      • uploadDir - Where uploaded files are intermediately stored during transfer before the contents is mapped intoreq.params. Does nothing ifmultipartFileHandler is defined.
      • multiples - if you want to support html5 multiple attribute in upload fields.
      • hash - If you want checksums calculated for incoming files, set this to eithersha1 ormd5.
  5. 編寫 CRUD API

    此處的 CRUD 僅作為演示使用,並不具備任何資料庫操作功能

    123456789101112131415161718192021 //獲取所有資訊server.get('/person', function(req, res){ res.send({message: 'Hello ,from GET!', data: 'All person'}); console.log('Get request from '+req.method);})//獲取某個person的資訊server.get('/person/:id', function(req, res){ res.send({message: 'Hello ,from GET!', data: {id: req.params.id}}); console.log('Get request from '+req.method+', request id is '+req.params.id);})//修改person資訊server.put('/person/:id', function(req, res){ res.send({message: 'Hello ,from PUT!', data: {info: req.params, id: req.params.id}}); console.log('Get request from '+req.method+', request id is '+req.params.id);})//新增personserver.post('/person', function(req, res){ res.send({message: 'Hello ,from post!', data: {id: id++, info: req.params}}); console.log('Get request from '+req.method+', new Person\'s info is :'+JSON.stringify(req.params)); // console.log(req);})
  6. 指定埠

    server.listen(1234, function() {
        console.log('%s listening at %s', server.name, server.url);
    });

  7. 簡易測試 API 是否可用

    測試用的工具是 postman,具體介紹可以移步至 官網

    • 測試 get 請求(不帶引數 id)
      get 請求不帶 id

    • 測試 get 請求(帶引數 id = 2)
      get 請求帶 id = 2

    • 測試 put 請求
      put

    • 測試 post 請求
      post

後語

使用 restify 框架搭建一個 RESTful API,比使用原生的 Node.js 搭建要方便,比使用 Express 框架要簡單方便。

restify 框架還有很多實用的功能有待大家挖掘。