Following the previous article, we slowly moved forward with the newbie front-end writing interface. Today I’ll focus on using KOA, which is a key step in completing the back-end interface. OK, get your little stool ready, I’m going to start the story.

What is the koa?

Let’s start with the official explanation: the next generation open Web framework based on the Node.js platform. The key word in this sentence is Web framework, so what is web framework? A similar framework is Express, which can be compared to her (sorry, code type is long, look who looks like her). If you are not familiar with Express, I want to raise some small animals in a pool. For example, I can raise some small fish in this pool. After a year, I can fish some small fish out. Or we could have some frogs in this pool, and then a year later we could have a group of adult frogs; Or we can raise some eels, and after a year we can get some adult eels……

We all know that the back and forth interaction requires HTTP requests. There is a third process called Request => processing data => Response, right? Let’s take another analogy: throwing young fish into the pool is like the request part of the HTTP request, the survival process of small fish in the pool is like the process of processing data, and fishing fish is like the response part. Koa, as a Web framework, pretty much covers both the drop and catch parts for us, and we just need to focus on the survival part of the pool. In other words: KOA handles request and response, all we need to do is write intermediate data processing, which is called middleware.

The word middleware is also very figurative, which is very similar to the middleman in our life. My hometown is in the south of China, known as the hometown of Fireworks, so my hometown is a manufacturer of fireworks. But there are often a group of people in our neighboring cities who buy our fireworks and sell them to others in need. This is the middleman. They control the source of the product from the producer (Request) and have a large number of end customers (response). What they do is a process of intermediate connection, or they can sell it at a high price and enjoy it first. Or small profits, expand market influence (these are in the middle of the process will happen). So what we’re relying on koA to do is this middleman thing.

After listening to the story of middlemen in my hometown, we come back to the real life and look at what we can do as middlemen in the program after we have security of supply (request) and end customer (response). Ok, let me share with you a small business.

Simple example

// app.js
const Koa = require('koa') const app = new Koa() // App.use ((CTX, next) => {const STR = new Koa() // app.use((CTX, next) => {const STR ='hello world'Ctx.body = STR}) // Bind port 3000 app.listen(3000)Copy the code

Next, we need to execute the command Node app to set up a Web server, and then enter localhost:3000 in the browser to see the text of Hello World on the page. Const Koa = require(‘ Koa ‘); Const app = new Koa() and app.listen(3000) are both required to set up a connection to the Web server. These two steps can be considered as request interface success. Use ((CTX, next) => {const STR = ‘hello world’; }) is part of the middleware process. This intermediate part is also very simple, it just defines a variable STR, and then it just goes away, and that’s all it does. Then Response outputs the result of what the intermediate link did, and we see hello World on the local server with port 3000.

Koa is designed to be very simple, as shown in the example above, where the server is set up and returned in a few lines of code. If we want to do something more complex, we need to rely on other middleware to do it. This is similar to vUE: you see, vue just provides the model of MVVM. If you want to do page routing, you should say to VueRouter: “Sister, please help me to do page routing.” If you want to do global data management, you should also say to Vuex: “Brother, help me with data management.”

And koA seems to know it, too.

When he wants to get the static resources of the server, he will say hello to KoaStaticCache: little sister, help me read the static files, and there will be delicious for you; When he wants to read the interface, he will say to KoaRouter: little brother, help me read the route, later help you score; When he wants to read a POST request, he says to KoaBodyparser, “Auntie, that request is POST, please get his request data for me.” So most of the time, the following plug-ins are often used in conjunction with KOA:

  • Koa-static-cache: static file proxy service
  • Koa – the router: routing
  • Koa-swig: template engine
  • Koa-bodyparser: Body parameter parsing for post requests

With these foundations in place, you are ready to move on to the project.

There are only two files server/app.js and server/routes/main.js in this project. Isn’t it super easy to just ask you?

Okay so what do we do when we parse these two files?

Interpreting project documents

app.js

Const Koa = require(const Koa = require('koa')
const KoaStaticCache = require('koa-static-cache')
const bodyParser = require('koa-body-parser')
const router = require('./routes/main') const app = new Koa() // Reads static files from the server, such as CSS, images, etc. App.use (KoaStaticCache(__dirname +'/static', {
    prefix: '/static',
    maxAge: false,
    gzip: true})) app.use(bodyParser({})) app.use(router.routes()) app.listen(3000)Copy the code

Use (KoaStaticCache(…)) ) This method. This is how static files are read from the server. Static files are resources such as CSS, images, etc. The configuration here refers to static files in the current folder, without caching, using gzip compression. But I didn’t include static files in this gua64 project (to teach you how to use them).

The second is app.use(bodyParser({})),app.use means to use the middleware. After this statement is executed, the corresponding entry parameter can be found in ctx.request.body. Again, I didn’t use the POST request in this demo, but I wrote it out to show you how this thing works.

App. Use (router.routes()). I put all the routes in the server/routes/main.js file. An interface is just a mapped address. For the specific interface information, see main.js. The previous ones are all fixed + configuration, see the official documentation will soon be able to start operating.

main.js

Router.get ('/findContent', async ctx => {
    const searchName = ctx.query.searchName || ' '// Find the data that contains a fieldlet {count, rows} = await Models.Contents.findAndCountAll({
        where: {
            [Op.or]: [
                {
                    name: {
                        [Op.like]: `%${searchName}%`
                    }
                },{
                    desc: {
                        [Op.like]: `%${searchName}%`
                    }
                }
            ]
        },
    })
    ctx.body = {
        code: 0,
        count: count,
        data: rows.map(item => {
            return {
                id: item.id,
                contentId: item.contentId,
                name: item.name,
                contentList: item.contentList,
                desc: item.desc,
                likeCount: item.likeCount
            }
        })
    }
})
Copy the code

Take a look at the query content interface above. Is it nothing like the simple example I wrote earlier? The middle step here is to go to the database and find the content of the condition, which is the variables count and rows, and then get them back in the data format that the front end wants, and then it’s gone. Simple enough to explode.

We’ll talk about how to query the contents of the database in the next video, that’s not the focus of this video.

conclusion

We started by looking at what KOA is and then using the pool example to compare what KOA does, we relied on what KOA can do and worked together to make the service work. Then I showed you how to use koA with a very simple example. Finally, I singled out koA in the project for analysis, and found that his application in the project was surprisingly similar to my example. So, in my opinion, the key point of KOA is the part of the app.use() function that handles the data. Once you get that part, you send it back to the front end and you’re done.

The next article will look at sequelize and the use of sequelize-CLI.

In addition, I created a new QQ group, the group number is: 1103713567 (full stack development springboard group). It is convenient for us to communicate with each other about front-end or project issues.