If you have principles, you’re not afraid of anything

He laughs at bruises who has never been hurt. — Romeo and Juliet

This paper mainly focuses on the establishment of KOA project, database connection configuration, static resource service, routing management. After reading the 3 minutes, you can also do the training course.


First look at the project catalog





Koa2 Project directory

Lib — node_modules — Routers — Static — app.js — package-lock.json — Webpack configuration file


Briefly, let’s talk about the idea of combining different parts of the project

1: App startup page, the entrance of the project, taking into account the whole project. So, dependencies, configuration, all in here 2: lib database management, the core work of back-end engineers is data, add, delete, change and check. (The method of each function is different, which is written here, so it needs to be separated. The later project is huge, and each function needs to be distinguished from separate file management.) 3: Static resources, why? React or VUE at the back end, front end are static resources, packaged here, closed cross-domain access, data security.

This is how small and medium sized projects are structured. Probably, it should be enough. Break it down. Break it down.

I. App.js project entry

The details of how to use it are all in the code,
Const Koa = require(' Koa ') const bodyParser = require('koa-bodyparser') const Router = require('koa-router') // static static = require('koa-cors') const path = require('path') const cors = require('koa-cors') // Static app = new Koa() const staticPath = './static' app.use(static(path.join(__dirname,)) Use (bodyParser()) app.use(bodyParser()) app.use(require('./ /routers/index').routes()) App.listen (3000) console.log(" Started successfully ")Copy the code
Interpretation of each middleware:
  • All imported resources must be installed in advance using NPM
  • Koa: The core components of the project
  • Koa-bodyparser: Middleware for body parsing. If you post forms, JSON data, or upload files, it’s not easy to get in KOA. This. Body gets directly from KOA with koA-BodyParser.
  • Koa-router: indicates the intermediate koA route.
  • Koa-static: The static resource service middleware of KOA
  • Path: indicates the path to obtain the middleware
  • Koa-cors: allows cross-domain requests. Assume that the Node service is on port 3000 and the React service is on port 3001. React gets the NODE json. Cross domain. Jsonp is much more troublesome. I don’t need it when I’m online.

Configure the middleware, set up the boot port, ready to go!!


2 :(router/index.js) routing management

No wordy, look at the code. Have a comment

const router =require('koa-router')(); // route const userModel = require('.. Router.get ('/',async(CTX,next) => {ctx.redirect('/index')}) router.get('/index',async(CTX,next)) Let HTML = '<h1> Get ('/ API ',async(CTX,next) => {let resd = "await" userModel.findAllPost() .then(result => { resd = JSON.parse(JSON.stringify(result)) // console.log(resd) }) ctx.body = resd }) module.exports= routerCopy the code
An explanation of the middleware
  • Import the routing component, which, note, performs functions. Add parentheses
  • The introduction of the database, the introduction of the increase, deletion, change and check method library, data management and talk about the back
  • Router.get () Routing middleware provides a method, the biggest convenience of KOA2 is the use of ES6 async asynchronous writing.
  • Request body, response body. Router.get (‘/index’) is the body of the request, which koA identifies and executes.
  • Response body let HTML = “the content of the response, after the complex programming, to get the content from the database processing after the content.
  • Ctx. body = the content returned by the body of the HTML response
Router. Get ('/index',async(CTX,next) => {let HTML = '<h1>' --gai </h1> 'ctx.body = HTML})Copy the code

All return JSON, let front-end engineers more busy bar, familiar with mysql, before the development of the architecture design, can save a lot of effort 0. 0


Lin database management and configuration

Two parts: 1 configuration (config.js), 2 methods (mysql.js)

// database configuration const config = {port: 3000, database:{database: '111', // USERNAME:'hez', // USERNAME:' aS62681***', // PASSWORD:' 3306', // HOST:'39.106.12.86' // url IP}} module.exports = configCopy the code

I annotated the password because it was online

const mysql = require('mysql') const config = require('./default') var pool = mysql.createPool({ host:config.database.HOST, user:config.database.USERNAME, password:config.database.PASSWORD, database:config.database.DATABASE }); let query = function( sql, values ) { return new Promise(( resolve, reject ) => { pool.getConnection(function(err, connection) { if (err) { resolve( err ) } else { connection.query(sql, values, ( err, Rows) => {if (err) {reject(err)} else {resolve(rows)} Connection.release ()})}})})} // Query the T1 database let findAllPost = function () { let _sql = ` SELECT * FROM hez1 ` return query(_sql) } module.exports={ findAllPost }Copy the code

Afraid, I am lazy!!

  • Configuration items are required because of the wired, offline, and heavy versions. So it’s much easier to separate configuration items
  • Once again, the core of backend work is data, real tips, add, delete, change and check
  • Mysql is written well and handles data very easily. Use JS functions to write SQL methods and encapsulate them. Exposed for use in individual components and modules.
Let findAllPost = function () {let _sql = 'SELECT * FROM hez1' return query(_sql)}Copy the code

Four: running the project

When the console returns data, success is indicated





Logs of the console

  • The page route enters/API and returns data, indicating success.
  • Of course, can also be ignored database, page return Lao Zi eat hot pot, you eat hot pot bottom material – GAI also means success

In fact, the project to git, submitted to the code management platform. After that, I will write another article about Git. The platform is probably the code cloud, Github.


Project code addressThe next article is about deploying a KOA project on a LINX server (CentOS 7.3 system). The content has koA2 service establishment, nginx agent, mysql installation, user management, system common instructions.

Js full stack engineers must see the url my personal url, (still under construction…)

Keep an eye on me for react, KOa, mysql, Vue, reactNative, etc apis, and tips. Follow me on wechat (yx626815494) or QQ (626815494) to have a look.