We already know what Koajs is, so as teenagers of the new age, we must know what it is and why. As a coder, it’s not important to know what it is, but how you use it. Again, please don’t tell me how to do it, please give me the code.
Koajs is available as a framework, or rather as an NPM repository, and to use it we must take several steps:
-
Find the appropriate file directory and run NPM init -y to initialize package.json.
-
Run NPM I KOA to install the KOA library locally
-
Run NPM i@types/koa-d to install the description of KOA locally. Facilitate intelligent prompt.
-
Create a new app.js file
-
With the initialization done, let’s insert some code into app.js:
const Koa = require("koa"); const app = new Koa(); app.use(async (ctx) => { ctx.body = "hello world"; }); app.listen(3000); Copy the code
-
Perform the node app. Js
-
Open your browser, type localhost:3000, and we’ll see hello World output.
After this wave, our simplest koAJS application is up and running. Let’s do a quick analysis of these lines:
1, const Koa = the require (” Koa “); Introducing the KOA package, which is all too familiar to NodeJS programmers, is importing an NPM package from node_modules.
2, const app=new Koa(); Initialize the Koa instance. Open koajs’s description and we can see
declare class Application< StateT = Application.DefaultState, ContextT = Application.DefaultContext> extends EventEmitter {
。。。。
export = Application;
Copy the code
The default export is a class, so we must create a new instance before we can use it.
3, app. Use (async (CTX) => {
ctx.body = “hello world”;
});
This code uses the use method, which is koA’s function to add middleware. For the principles of KOA middleware functions, please refer to the official documentation.
4, app. Listen (3000); Listen on port 3000, which is why we have to type localhost:3000 in the browser to access it.
After this wave of simple operations, one of our small KOA applications is up and running. But we’ve only scratched the surface, covering the middleware functions in KOAJS, async in the use method, what type CTX is, and how KOAJS is executed.
Once these principles are understood, we can write a framework for KOAJS without a problem.
Everything needs a beginning, we have to build interest to move forward.
Koajs is a library with very good code structure and strong reference value. Even if we do not use it in our work, we can better understand the writing mode of async&await function and middleware by learning it, and it can also be applied to our daily coding.
Koajs itself does not contain middleware, so it is lightweight, but we must have the ability to write middleware and a way to look at and apply it.
The KOAJS Growth Path will continue to dissect each technology point.