使用node.js建立RESTful 的API Service, 能夠選擇的框架有 hapi, express 等。 這裏筆者推薦使用 hapi框架,會自動建立model 的 CRUD endpoints ,簡單易行。 使用過express, 仍是有很多坑的, 尤爲在client和server端數據交互時,使用中間件body-parse 問題很多, 筆者將在下一篇文章詳述。java
安裝最新版本 Node.js . Node.js官方下載node
使用 Visual Studio Code 打開一個空的文件夾, 好比 c:\work\ionic\hapi-demo-service ,git
打開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
安裝開發包。依次在終端中運行 npm i Hapi --save , npm i mongoose --savemongodb
安裝 rest-hapi插件. 終端中輸入 npm i rest-hapi --saveexpress
生成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();
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; };
"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' }
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
建立一個新的User瀏覽器
使用robot 3T 在 mongo DB 中查看結果,
最後,附上源代碼連接 : https://github.com/amincai/hapi-demo-service
下載到本機後,終端運行 npm i
行文倉促,不免有所錯漏或失誤,歡迎批評指正。
@caiyaming