1. 程式人生 > >ionic 後臺Api服務, 使用rest-hapi , node.js 創建 RESTful API Service , 附完整源代碼

ionic 後臺Api服務, 使用rest-hapi , node.js 創建 RESTful API Service , 附完整源代碼

host restful view iss swagger put imageview clas opened

使用node.js創建RESTful 的API Service, 可以選擇的框架有 hapi, express 等。 這裏筆者推薦使用 hapi框架,會自動創建model 的 CRUD endpoints ,簡單易行。 使用過express, 還是有不少坑的, 尤其在client和server端數據交互時,使用中間件body-parse 問題不少, 筆者將在下一篇文章詳述。

  1. 安裝最新版本 Node.js . Node.js官方下載

  2. 使用 Visual Studio Code 打開一個空的文件夾, 比如 c:\work\ionic\hapi-demo-service ,

  3. 打開Visual Studio Code的終端,輸入 npm init , 出現如下所示的信息, 直接按回車使用默認設置即可。也可輸入內容替換默認信息。知道出現提示 : is it OK? (yes) ,輸入yes 即可。 這時會在hapi-demo-service根目錄下生產package.json文件。

C:\Work\Ionic\hapi-demo-service>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (hapi-demo-service) hapi-demo-service
version: (1.0.0)
description: hapi demo service
entry point: (index.js)
...
Is this OK? (yes) yes

  1. 安裝開發包。依次在終端中運行 npm i Hapi --save , npm i mongoose --save

  2. 安裝 rest-hapi插件. 終端中輸入 npm i rest-hapi --save

  3. 生成service入口類(或者是主類) touch index.js. (index.js 是默認設置, 請參考package.json文件,main節點。
    將如下代碼拷貝到index.js

技術分享圖片
const Hapi = require("hapi");
let mongoose = require(‘mongoose‘);
let RestHapi = require(‘rest-hapi‘);
 
 
async 
function api(){ try { let server = Hapi.Server({ //Amin: host is important for IOS system. If missing host, the in IOS, it would use machinename.local to replace localhost //if post or get request raised , there‘s no response. host: ‘localhost‘, port: 3001 }); let config = { appTitle: "hapi-demo-service", version: ‘1.0.0‘, authStrategy: false , mongo: { URI: ‘mongodb://localhost/hapi-demo-service‘ } }; config.embedAssociations = false; await server.register({ plugin: RestHapi, options: { mongoose, config } }); await server.start(); console.log("Server ready", server.info); return server; } catch (err) { console.log("Error starting server:", err); } } module.exports = api();
View Code

  1. 生成model類。 VS code 打開終端。輸入 mkdir models, 然後再輸入 touch models\user.model.js , 此時會生成 user model。 註意目錄名稱必須是 models , 文件名稱需遵循格式 {model name}.model.js.
    將以下代碼拷貝到 user.model.js
技術分享圖片
module.exports = function (mongoose) {
  let modelName = "user";
  let Types = mongoose.Schema.Types;
  let Schema = new mongoose.Schema({
    email: {
      type: Types.String,
      required: true,
      unique: true
    },
    password: {
      type: Types.String,
      required: true,
      exclude: true,
      allowOnUpdate: false
    }
  });
  
  Schema.statics = {
    collectionName: modelName,
    routeOptions: {}
  };
  
  return Schema;
};
View Code

  1. 好,大功告成。可以運行程序了。終端輸入 node index.js 。 當然,也可以使用 npm start來運行。 將 "start": "node index.js" 添加到package.json的scripts 節點中。
    以下是更新後package.json的 scripts 節點
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },

運行成功界面如下

C:\Work\Ionic\hapi-demo-service>node index.js  。
以下是運行界面
[14:29:03.251] 16856 LOG      api/mongoose-init — Connecting to Database...:
[14:29:03.260] 16856 LOG      api/mongoose-init —      URI: `mongodb://localhost/hapi-demo-service`
[14:29:03.277] 16856 LOG      api/mongoose-init — mongoose connected
[14:29:03.278] 16856 LOG      api — Initializing Server...
[14:29:03.367] 16856 INFO     api/register-hapi-swagger — hapi-swagger plugin registered
[14:29:03.367] 16856 INFO     api/register-MrHorse — MrHorse plugin registered
Server ready { created: 1530253743241,
  started: 1530253743467,
  host: ‘CNSHAEL3Z5Z9H2‘,
  port: 3001,
  protocol: ‘http‘,
  ...
  address: ‘0.0.0.0‘ }

  1. 瀏覽器中輸入 : http://localhost:3001 。使用rest-hapi框架的好處是: 會自動生成CRUD的endpoints.
    測試api方法,這裏推薦使用postman. 當然,在瀏覽器中也是可以測試的。
DELETE /user        Delete multiple users
POST /user          Create one or more new users
GET /user           Get a list of users
DELETE /user/{_id}  Delete a user
GET /user/{_id}     Get a specific user
PUT /user/{_id}     Update a user

運行界面截圖:

技術分享圖片
image.png

創建一個新的User

技術分享圖片
image.png

使用robot 3T 在 mongo DB 中查看結果,

技術分享圖片
image.png

最後,附上源代碼鏈接 : https://github.com/amincai/hapi-demo-service
下載到本機後,終端運行 npm i

行文倉促,難免有所錯漏或失誤,歡迎批評指正。

@caiyaming

ionic 後臺Api服務, 使用rest-hapi , node.js 創建 RESTful API Service , 附完整源代碼