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

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

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

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

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

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 --savemongodb

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

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

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"
  },

 

運行成功界面以下json

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

 

運行界面截圖:api

 

image.png
image.png

建立一個新的User瀏覽器

 

image.png
image.png

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

 

image.png
image.png

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

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

@caiyaming

相關文章
相關標籤/搜索