This article will show you how to build a complete MVC and RESTAPI project based on Node-koa, which encapsulates the basic functions of routing, template engine, static file loading, first describes the installation start and directory structure of the project, and then illustrates the building and use of MVC through a simple login page. , through a person form of the additions and deletions to explain the construction and use of RESTAPI, and finally will be a simple description of the implementation of the module;
Full Project address: Https://github.com/pangyongsheng/node-koa-REST-API
one, the nextinstall and start the project
Download: git clone https://github.com/pangyongsheng/node-koa-REST-API.git
Switch to directory: CD KOA
Install dependency Package: NPM Install
Startup Project: NPM run Start
Visit: http://127.0.0.1:3000/
The interface is as follows:
Ii. Description of the project directory structure
KOA
├──app.js service startup file
├──controller.js traverse the Controllers folder to add all the interface files to the route
├──rest.js package RESTAPI returns data processing, simplifying API notation--rest methods
├──templating.js package template engine loading view template file,--render method
├──static-file.js Package static file loading method
│
├──controllers All interface files under this directory, such as:
├──api.js Restapi interface
├──index.js Home Interface
├── ...
├──view You place the view template file under this directory, you can use the Nunjucks template syntax:
├──base.html Basic template-header and footer
├──index.html Home
├── ...
├──server The directory to place data processing class JS file: such as the extraction of similar business data processing methods
├──server.js
├── ...
├──data placing database processing files under this directory
├──config.js Database configuration file
├── ...
├──static to place the front-end static files, such as some front-end class libraries, UI, and pictures, etc.
├──css
├──js
├── ...
├──package.json
Third, MVC build landing page
1, write the page code(1) Create the base.html file in the view directory, write the page header and the tail code as the View section, where we use the nunjucks template syntax, so that other pages can call the base.html code directly;
page code For example, this contains the document declaration and
Other pages can call base.html directly and then write the intermediate content (i.e. {% block main%} to {% endblock});
Note here that the <title> tag is {{title}}, which requires us to pass in the header Name field directly when the page is called;
(2) Create the index.html in the View ' directory, write the login page form code;
Here we first introduce the public view section through {{% extends "base.html"%}}, and then write the login form in {{%block mian%}} and {{%block end%}};
2. Add an Access interface(1) Create the Index.js file in the Controllers directory, as the interface file of the login page;
Here, ' get/' means the request is a GET request URL of/That is the default path
Ctx.render is an already sealed method, passing in the page file to be returned, here we return to the login page, and index.html page
The argument {title: ' KOA '} is the parameter that we passed to the page template, and the value reserved in the previous template <title>
(2) Visit hostlocal:3000/to see the following login page:
3. Add Form Processing interface (POST)
The previous step to complete the function of the login page, when the login click Submit, the POST request will be submitted to/signin,
First we follow the above way in the view directory to write page login success signin-ok.html and failure sigin-fialed.html; (detailed code see project)
Write the signin.js in the Controller directory to process the login submission to the Post/signin information;
' Post/signin ' indicates the request method and the request URL is/signin
Get request parameters by Ctx.request.body to determine if the data is correct and return the corresponding page
Iv. RESTAPI Realization of table information additions and deletions
1. Create a Personnel Information Form page(1) In the view directory, write the views file userlist.html (and add the JS logic code to the page)
in order to simplify the code here using VUE bidirectional binding implementation, Note: the template compilation in Vue and the Nunjucks compilation {{}} symbol will conflict, you need to modify the Vue compilation format, configure in Vue delimiters:[' ${', '} ']
The page uses the v-for loop to display the table, adding a method in JS GetList api/userlist get all the data through the interface, and call the change method in the Vue life cycle created. (Detailed code see project view/userlist.html)
The Get/api/userlist interface is described in the next section
(2) Add the Access interface under the Controllers directory List.js
Similar to the previous logon method, the Access interface is Get/user
(3) Visit Hostlocal:3000/user to see the following page:
After the completion of the page, we will implement the buttons on the page by the Restapi interface to modify the function
2. Write a rest interface to get all personnel information(1) In the data directory to create Data-userlist.js as the analog data, (analog database return data, for the convenience of not using the database)
(2) Write user.js in the server directory to write data processing methods for the rest interface to use
This creates the Getalluser method to return all the data in the Data-userlist directly
(3) Create api.js in the Controllers directory to place the Restapi interface
The Ctx.rest method encapsulates functions such as return data and error handling, where the Restapi interface function can be achieved by directly passing in the returned data object.
(4) Accessing the Calling interface
In the previous section we called the interface, returned the People list data, and presented the data to the view through the list rendering.
2. Add Gender screening function(1) Add Filter button to page and bind event, call Gender filter interface
(2) Add api/userlist/m and api/user/f interfaces to Api.js, respectively, to return a list of male and female personnel information
(3) Add the Get data method in Server/user.js
3. Add User function(1) Adding input boxes and buttons to the page, binding add events
Click Save after the put mode like interface api/adduser Add user information, in a successful callback call GetList method, get the latest user information;
(2) Add put interface in Api.js api/adduser-call AddUser Method (3) Add AddUser method in Server/user.js to process the added data
User name, gender, age has front-end value, ID is arranged by the background according to the sequence number, and then deposited into the array
4. Delete users (1) Bit page Delete button bind event and write Delete method send delete request to Api/userlist interface
In the table we have added the Delete button and bound the Del method, and pass the parameter ID, the following directly see Del method
The $tttp.delete method is called in the Del method to send a delete request to api/userlist and pass in the parameter ID (' +x ' in the code) and then delete the data from the view in the success callback (you can also call the GetUser method directly here)
(2) Add the delete request pretext in Api.js, invoke the method in the interface Sever/user.js (note here to get the parameter method)
Here we get the ID of the reference in the previous step by ctx.parames.id, here we take the method of passing the parameter in the server
(3) Adding the Delete data method in Server/user.js
5. Modify the Data(1) Add an editable attribute to the section of the table in the page form (a modifiable lattice) and add a Save button to the corresponding row action area, without saving the button to add the SEv method
Then write the SEv method, through the JS operation Dom method to get the property values in the table, as the modified parameter call send POST request to the background modification information, call the GetList method in the success callback query the latest data display to the page, promote the Save success
(2) Adding the Modify information interface in the Api.js
(3) Write the modified information method under Server/user.js (this ID is used as an index or a unique identifier)
At this point, the implementation of MVC and RESTAPI to add and delete features have been added, the project also has a search function and other screening methods similar to do not explain;
Dome used in the front-end part of the vue.js, bootstrap, node module used in Koa-router, koa-cors and other modules details see Package.json;
The test module can not be described here, but in the project has been added, can be used;
The function of each module is also explained, the realization method can directly see the code, there is a clearer comment;
Node-koa Build mvc/restful API Project