Using node. js to create a RESTful API Service, you can choose a framework that has HAPI, express, and so on. The author recommends using the HAPI framework, which automatically creates the model's CRUD endpoints, which is simple and easy. Using Express, there are a lot of pits, especially in the client and server side data interaction, the use of middleware body-parse problems, the author will be detailed in the next article.
-
Install the latest version of node. js. node. JS Official Download
-
Use Visual Studio Code to open an empty folder, such as C:\work\ionic\hapi-demo-service,
-
Open the terminal for Visual Studio code, enter NPM init, and then press ENTER to use the default settings as shown below. You can also enter content to replace the default information. Know that there is a hint: Is it OK? (yes), enter Yes. The Package.json file is then produced in the Hapi-demo-service root directory.
C:\WORK\IONIC\HAPI-DEMO-SERVICE>NPM Initthis utility would walk you through creating a Package.json file. It is covers the most common items, and tries to guess sensible defaults. See ' NPM help json ' for definitive documentation on these fieldsand exactly what they do. Use ' npm install <pkg> ' afterwards to install a package andsave it as a dependency in the Package.json file. Press ^c at no time to Quit.package name: (hapi-demo-service) Hapi-demo-serviceversion: (1.0.0) DESCRIPTION:HAPI demo Ser Viceentry point: (index.js) ... Is this OK? (yes) Yes
-
Install the development package. Run NPM i Hapi--save in the terminal sequentially, npm I mongoose--save
-
Install the Rest-hapi plugin. Input NPM i rest-hapi--save in terminal
-
Generates a service entry class (or main Class) touch Index.js. (Index.js is the default setting, refer to the Package.json file, main node.)
Copy the following code to Index.js
Const HAPI = require ("Hapi"); let Mongoose= Require (' Mongoose '); let Resthapi= Require (' Rest-hapi '); AsyncfunctionAPI () {Try{Let server=Hapi.server ({//Amin:host is important for IOS system. If missing host, the in IOS, it would with 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); returnserver; } Catch(Err) {Console.log ("Error Starting server:", err); }} module.exports= API ();View Code
- Generates the model class. VS code opens the terminal. Enter mkdir models, and then enter Touch Models\user.model.js, and the user model is generated. Note the directory name must be models, and the file name should follow the format {model name}.model.js.
Copy the following code to User.model.js
Module.exports =function(Mongoose) {Let modelname= "User"; Let Types=Mongoose. Schema.types; Let Schema=NewMongoose. Schema ({email: {type:Types.String, Required:true, Unique:true}, Password: {type:Types.String, Required:true, exclude:true, Allowonupdate:false } }); Schema.statics={collectionname:modelname, routeoptions: {}}; returnSchema;};View Code
- All right, it's done. You can run the program. Terminal input node index.js. Of course, you can also use NPM start to run. Add "Start": "Node Index.js" to the scripts node of the Package.json.
The following is an updated Package.json scripts node
"Scripts": { "test": "Echo \" Error:no test specified\ "&& exit 1", "Start": "Node Index.js" },
Run the successful interface as follows
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 registeredserver Ready {created:1530253743241, started:1530253743467, Host: ' Cnshael3z5z9h2 ', port:3001, protocol: ' http ', ... Address: ' 0.0.0.0 '}
- In the browser, enter: http://localhost:3001. The advantage of using the REST-HAPI framework is that it automatically generates CRUD endpoints.
Testing the API method, it is recommended to use postman. Of course, it can also be tested in the browser.
Delete/user Delete multiple userspost/user Create one or more new Usersget/user Get a list of Usersdelete/ USER/{_ID} Delete a userget/user/{_id} Get a specific userput/user/{_id} Update a user
Operating interface:
Image.png
Create a new user
Image.png
Use robot 3T to view the results in MONGO DB,
Image.png
Finally, attach the source code link: https://github.com/amincai/hapi-demo-service
After downloading to this machine, the terminal runs NPM I
Hasty, inevitably some mistakes or errors, welcome criticism.
@caiyaming
Ionic Backend API services, using REST-HAPI, node. js to create RESTful API service with full source code