Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the koa framework of node.js

Shulou Source: shulou.com Published: 2022-06-03 20:05:08 10月17日 Update

This article will explain in detail how to use the koa framework of node.js. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

Koa-- the next Generation web Development Framework based on Node.js platform

Koa is built by Express's original team and is committed to becoming a smaller, more expressive, and more robust Web framework. Writing web applications with koa can avoid repetitive and tedious nesting of callback functions and greatly improve the efficiency of error handling. Koa does not bind any middleware in kernel methods, it only provides a lightweight and elegant library of functions, which makes it easy to write Web applications. The development idea is similar to express, the most important feature is that it can avoid asynchronous nesting. Koa2 makes use of the async/await feature of ES7 to greatly solve the trouble brought to us by asynchronism when we do nodejs development.

English official website: http://koajs.com

Chinese official website: http://koajs.cn

1.koa

Install the koa package: npm I-S koa@latest

Introduce: const koa = require ("koa")

Instantiate object: const app = new koa

Through instance operation, the function specifically used for client request is called middleware and is registered with use ().

Asynchronous async; use must be used in the use () function, but it can be called countless times

There are two parameters:

A) ctx: context, request and response objects for node, where the native req and res properties of node are not recommended, and koa-encapsulated requset and response properties are not recommended

B) next: next () to transfer control this time to the next middleware.

The last middleware makes no sense using next (), and returns to the upper level after executing the control until the first.

1. Use demo of next parameter

Const Koa = require ("koa"); const koa = new Koa (); / / Middleware 1koa.use (async (ctx, next) = > {console.log ("1, receive request control"); await next (); / / transfer control to the next middleware console.log ("1, return request control");}) / / Register the middleware to the instance of koa / / Middleware 2koa.use (async (ctx, next) = > {console.log ("2, receive request control"); await next (); console.log ("2, return request control";}); / / Middleware 3koa.use (async (ctx, next) = > {console.log ("3, receive request control"); console.log ("3, return request control") }); koa.listen (3000, () = > {console.log ("start listening on port 3000");})

Note: there is no next () in the middleware and the following middleware will not be executed

Access the effect picture of localhost:3000

Note: there will be two operations because the icon icon will also request once.

The use of the 2.ctx parameter demo

Const Koa = require ("koa"); const koa = new Koa (); koa.use (async (ctx, next) = > {ctx.body = "body can return data,"; ctx.body + = "can be called multiple times,"; ctx.body + = "No end ()";}); koa.listen (3000, () = > {console.log ("listening start");})

Effect:

Ctx.url, ctx.path, ctx.query, ctx.querystring, ctx.state, ctx.type

Const Koa = require ("koa"); const koa = new Koa (); koa.use (async (ctx, next) = > {ctx.body = ctx.url; ctx.body = ctx.path; ctx.body = ctx.query; ctx.body = ctx.querystring;}); koa.listen (3000, () = > {console.log ("listening start");})

Visit http://localhost:3000/path?name=sjl&age=18 as an example, and the effect image:

1. Url: the entire path

2. Path: non-query part

3. Query: convert the query part to JSON object

4. Querystring: convert the query part to a string

5. Does ctx.state and ctx.type indicate status and type?

two。 Simple crawler exercise

Install the request,cheerio module

Npm I-S request: request module npm I-S cheerio: crawl page module (JQ core)

Case of crawling web page data (random web page)

/ / Import module const request = require ("superagent"); / / Import request module const cheerio = require ("cheerio"); const {join} = require ("path"); const fs = require ("fs"); let arr = [], / / store data reg = /\ n |\ saccountablesg, / / use url = "https://www.shiguangkey.com/course/search?key=%E5%89%8D%E7%AB%AF/";" in replace Request .get (url) .end ((err, res) = > {const $= cheerio.load (res.text)) / / use $(".course-item") .each ((I, v) = > {/ / v current incoming dom) to treat the tags in the string as dom Find the exact dom node const obj = {imgSrc: $(v). Find ("img"). Prop ("src"), price: $(v). Find (".fr span"). Text (). Replace (reg, "), total: $(v) .find (" .item-txt "). Text (). Replace (reg,") Href: join (url + $(v). Find (".cimg") .prop ("href"))} Console.log (join (url + $(v). Find (".cimg"). Prop ("href")); / / splice arr.push (obj); / / put objects into an array}); fs.writeFile (". / sjl.json", JSON.stringify (arr)); / / write crawled data to the document}) This is the end of this article on "how to use the koa framework of node.js". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

Tags: Middleware control control module framework function object data parameter instance effect article web page part development query monitor character string attribute Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft macOS Linux vpn Shulou Tech Info