Yesterday, I had a spare time to browse THE API of KOA and made a small table demo for adding, deleting, modifying and checking. It took about half a day to add and check the API with four interfaces and small front-end interface. So KOA is really a simple and quick library to develop

You should already know how to operate a database. I’m using mongodb, but if you can’t go to my first two articles, it’s easy to get started. I’m using robo3.0

Because the front end is very simple, I put it under public, the project address github.com/ZhaoyangRao…

Let’s take a look at the result

Structure of back-end code

├─ │ ├─ ├─ ├─ ├─ ├─ ├─ ├─ ├─ ├─ ├─ / / the corresponding operating table, here is omitted │ ├ ─ ─ middleware / / custom middleware │ ├ ─ ─ models / / definition of the table structure │ │ └ ─ ─... │ ├ ─ ├ ─ garbage // └ │ ├ ─ garbage // ├─ exercises, ├─ exercises, exercises, exercises, exercises, exercises, exercises, exercises, exercises, exercises, exercises, exercisesCopy the code

As an aside, there is an idea that runs through the whole code at the front end and back end. MVC is also embodied in the directory and function here. Models are M,controllers are C, routes are similar to the V presentation layer, which is the request interface thrown out.

Overview of main Contents

Appjs entry file

The entry file has no business code and does a few important things,

1.require('koa'Mongoose mongoose is a library provided by nodeJS to connect to mongodb. Call routes 4.require('koa2-cors'); require('koa-body'); I have also introduced two more useful libraries, one for cross-domain and one for POST requests and file downloadsCopy the code

Connect to the database directory

First of all, the database belongs to layer M. You can see that mongoose is connected to mongodb in the Models.

Schema(equivalent to a database template, data structure) Mongoose. Model (simple understanding is through mongoose. Model you can operate on the corresponding data in the database ())Copy the code

Controllers directory

That is, the operations you define call the method controllers in the data layer

Utils tools

Some common methods, formatting time and so on

Middleware Custom middleware

You can write something that encapsulates the Request Response

Routes (interface)

The exposed interface and the callbacks that the corresponding interface calls controllers, which then operate the Models

Summary, this is just my own definition of the directory, and their own one-sided understanding, specific code annotations in the file, after all, only read and write half a day, there are wrong places welcome to correct