Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
Node.js installation and environment configuration, simple use of NPM, Koa framework scaffolding and common middleware were introduced in the previous article “Developing Restful API services using The Koa Framework of Node.js”. In this article, we will set up an API service framework in detail and use the common middleware of Koa.
The project structure
Koa-api -- Project name Controller -- Controller config -- Configuration file Model -- Model Entity object Routers -- Static -- Static resource utils -- tool library app.js Project startup fileCopy the code
The controller
Handler methods specify URL mappings, process business logic, respond to user requests, get request data, and return data.
Create a UserController (usercontroller.js) in the controller folder.
/** * UserController */ const result = require('.. /model/Result'); Class UserController {// userInfo async userInfo(CTX, next) {//TODO gets userInfo // result.code = 1; result.data = { name: 'admin', pwd: "12346" }; Result. MSG = "commit successfully "; ctx.body = result } } module.exports = new UserController();Copy the code
Entity model
Corresponding to the table structure entities in the database, you can also customize the generic entity objects.
Create a uniform return data object (result.js) and user information (userinfo.js) in the model folder.
/ / module.exports = {code: 0, data: null, MSG: ""}Copy the code
Route (KOA-Router)
Routing is the ability to access through URLS, pass parameters, send and get data through GET, POST, etc.
Create a routing file (index.js) in the routers folder
/** */ const Router = require('koa-router'); const userCtrl = require('.. /controller/UserController'); const config = require('.. /config'); Let router = new router ({prefix: config.apiprefix}); let router = new router ({prefix: config.apiprefix}); Router.get ('/user/userinfo', userCtrl.userinfo); // User module router.get('/user/userinfo', userCtrl.userinfo); module.exports = router;Copy the code
Static resources (KOA-static)
Static Web hosting service KOA -static middleware is mainly used to deal with static resources, can directly access files through THE URL, such as: images, styles, Javascript, JSON files, etc., can also set up picture cache.
/* / const static = require('koa-static'); Const staticPath = './static'; app.use(static( path.join(__dirname, staticPath) ));Copy the code
Tools
Encapsulate some public methods needed by the project into a class library, such as Cookie, sessionStorage, localStorage, AXIos, etc
Create utility library files (tools.js, request.js) in folder utils
Export setCookie = function setCookie(name, value, time) { if (time) { let strsec = getsec(time) let exp = new Date() exp.setTime(exp.getTime() + parseInt(strsec)) document.cookie = name + '=' + escape(value) + '; Expires =' + exp. ToGMTString ()} else {document.cookie = name + '=' + escape(value)}} // Read cookies export let getCookie = function(name) { let reg = new RegExp('(^| )' + name + '=([^;] (*). |$)') let arr = document.cookie.match(reg) return arr ? unescape(arr[2]) : Var exp = new Date() exp. SetTime (exp. GetTime () -1) var cval = getCookie(name) if (cval ! = null) { document.cookie = name + '=' + cval + '; expires=' + exp.toGMTString() } }Copy the code
The configuration file
Used to manage and set the values of some common constants used in the project, such as: database configuration, log configuration, third party request service, etc.
Create config file (index.js) in config
/** * configuration file: database configuration/log configuration/service configuration /...... */ /** * set API uniform path prefix */ const apiPrefix = "/ API "; /** * MySql dataBase configuration */ const dataBase = {port: 3000, // dataBase: {host: 'localhost', port: '3306', user: 'root', password: '123456', database: 'test' } }; module.exports = { apiPrefix, dataBase };Copy the code
Start the file app.js
This is the startup file of the project, which is also the most important content. It initializes the loading of other modules. Such as: route loading, static resource loading, log module loading, cross-domain module, start listening port and so on.
const Koa = require('koa'); const path = require('path'); const logger = require('koa-logger'); // log middleware const Router = require('koa-router'); // const bodyParser = require('koa-bodyparser'); // const static = require('koa-static'); // const cors = require('koa-cors'); // More than one of these two areas needs to be connected to the phones. // More than one area needs to be connected to the phones. // // Routing service const app = new Koa(); App.use (cors()) // Allow cross-domain access to app.use(logger()); // Run log content custom app.use(bodyParser()); Const staticPath = './static'; app.use(static( path.join(__dirname, staticPath) )); // Let routerHome = new Router(); Routerhome.get ('/', async(CTX, next) => {ctx.body = 'Welcome to Koa API! '; }); / / load all routing app. Use (routerHome. Routes ()). The use (routerHome. AllowedMethods ()); app.use(registerRouters.routes()).use(registerRouters.allowedMethods()); Listen (3000, () => {console.log('Koa API starts at port 3000'); Console. log("API access: http://localhost:3000"); });Copy the code
If the content of the article to write the existence of problems, welcome message pointed out, let us common exchange, common discussion, common progress ~~~
If the content of the article is helpful to you, move your little hands to praise, encourage, give me the power to move forward.
“Welcome to the discussion in the comments section. The excavation authorities will draw 100 nuggets in the comments section after project Diggnation. See the event article for details.”