当前位置:网站首页>Introduction to koa (II) building the koa program
Introduction to koa (II) building the koa program
2022-06-24 16:41:00 【Uncertainty】
1 Project structures,
1.1 initial directory
install mkdir koa-demo && cd koa-demo && npm init -y && npm i koa --save && code .
stay package.json Configuration in file :
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
}1.2 New root index.js file
const Koa = require('koa')
const app = new Koa()
// middleware
app.use((ctx) => {
// ctx.body amount to http.createServer((req, res) => { res.end(' Hello , Uncertainty of measurement ') })
ctx.body = ' Hello , Uncertainty of measurement '
})
app.listen(3000, () => {
console.log(' monitor 3000 port ')
})
ctx.bodyIs the data returned to the front end , Previous development wasMVCPattern , The back end is directly rendered , Back to the front end , You can write like thisctx.body = '<h1> Hello , Uncertainty of measurement </h1>', In this way, the page can render labels directly ; But the current projects are separated from the front end and the back end , The back end directly returnsJSONdata , Get the front end and render it , thereforeKoaThe data returned is like thisctx.body = [{name: 'uncertainty'}, {name: ' Uncertainty of measurement '}], I hope my expression makes you understand .
perform npm start
Open the browser , Input http://localhost:3000/
Of course, you can now use the browser to view , the reason being that get request , But it is recommended that you install postman, It can be easily tested later post Request or upload file function .postman Download address .
1.3 Use postman request http://localhost:3000/
But every time you change the code here, you need to restart the service , Not very convenient , Here we install nodemon Auxiliary tool , It will refresh automatically after changes , It can be installed globally or under the current project , I will install it globally npm i nodemon -g.
Modify the startup command to "start": "nodemon index.js" (nodemon Will help us monitor js, mjs, json Changes in documents , Start the program automatically )
2 Implement a simple Koa
Everybody knows ,Koa It's right node Encapsulation , Let's start with a simple service implementation :
- New file
application.jsUseKoaWhen isnewExample , So you need to implement a class ,listenMethod listening port ,useMethod to mount the middleware , as follows :let http = require('http') class Application{ constructor() { this.callbackFunc } // Turn on http srever Pass in callback listen(...args) { let server = http.createServer(this.callback()) server.listen(...args) } /** * Mount callback function * @param {*} fn Callback handler */ use(fn) { this.callbackFunc = fn } /** * obtain http server The required callback function */ callback() { return (req, res) => { this.callbackFunc(req, res) } } } module.exports = Application - newly build
example.jsfile Put theapplication.jsThe file import let simpleKoa = require('./application') let app = new simpleKoa() app.use((req, res) => { res.writeHead(200) res.end('hello, uncertainty') }) // This monitoring 8000 app.listen(8000, () => console.log(' monitor 8000 port ')) - Carry out orders
nodemon example.js
3 middleware
Koa Is a middleware framework , There is no middleware bundled with it ( The core code is simple ). It does not support many functions , All functions can be realized through middleware expansion . By adding different middleware , Implement different requirements , To build a Koa application .Koa The middleware is the function , Now it's basically async function .
- app.use() Is used to register middleware and must be a generator function ( There are judgments in the source code , Later versions will be removed ,2.0 For downward compatibility )use(fn) { if (typeof fn !== 'function') throw new TypeError('middleware must be a function!'); if (isGeneratorFunction(fn)) { deprecate('Support for generators will be removed in v3. ' + 'See the documentation for examples of how to convert old middleware ' + 'https://github.com/koajs/koa/blob/master/docs/migration.md'); fn = convert(fn); } debug('use %s', fn._name || fn.name || '-'); this.middleware.push(fn); return this; }
Generator function :
generatoryesES6A new special function , adoptfunction*Statement , Function body throughyieldTo indicate the pause point of the function , This function returns an iterator , And the function executes toyieldPause before the statement , Then call the iterator that is returnednext()Method to executeyieldsentence
We can also use generator functions as middleware ( Not recommended ):
const Koa = require('koa')
const app = new Koa()
app.use(function *(next){
console.log(1)
yield next;
console.log(3)
this.body = ' Hello , I'm not sure '
})
app.use(function *(next){
console.log(2)
yield next
})
app.listen(3000, () => {
console.log(' monitor 3000 port ')
})KoaThe middleware is cascaded in a more traditional way , Abandon the past node Complex code logic caused by frequent callback functionsKoaMany intermediate bond functions will form a processing chain , Each intermediate key function can do something of its own , And then usenext()To call the next intermediate key function- The intermediate key must be a function , It can be an asynchronous function : adopt es7 Medium async and await To deal with it
useTwo objects are encapsulated inside :ctx,next
ctxyescontextIs generally called context , It mainly includesrequestandresponse.bodyyeshttpThe response body in the protocol ,headerRefers to the response header , If you want to throw exceptions, you can directly usectx.throw(500, ' Abnormal interface '),ctx.statusSet status code ,ctx.urlGet requestURLetc. .nextPlay the role of serial middleware , By callingnextfunction , Give execution to the next middleware . The last middleware does not use this function .
4 Write your own middleware
4.1 log middleware
The log module is also an indispensable part of online , The perfect log system can help us quickly troubleshoot the problems on the outgoing line . adopt Koa middleware , We can implement our own log module ( Of course, you can directly use the existing libraries in the community ):
- newly build
logger.jsconst fs = require('fs') module.exports = (options) => async (ctx, next) => { const startTime = Date.now() const requestTime = new Date() await next() const ms = Date.now() - startTime let logout = `${ctx.request.ip} -- ${requestTime} -- ${ctx.method} -- ${ctx.url} -- ${ms}ms` // Output log file fs.appendFileSync('./log.txt', logout + '\n') }const Koa = require('Koa') const app = new Koa() const logger = require('./logger') app.use(logger()) app.listen(3000, () => { console.log(`Server port is 3000.`) }) - Import file
logger.jsfile
4.2 token verification
Separate front and rear development , We often use JWT To authenticate , among token Generally placed on HTTP In the request Header Authorization Field ( Later on ), The back end of each request must be verified , It is impossible to write judgments for every interface ,Koa By writing middleware to achieve token verification .
- establish
token.jsmodule.exports = (options) => async (ctx, next) { try { // obtain token const token = ctx.header.authorization if (token) { try { // verify Function validation token, And get user related information await verify(token) } catch (err) { console.log(err) } } // Go to the next middleware await next() } catch (err) { console.log(err) } }const Koa = require('Koa') const app = new Koa() const token = require('./token') app.use(token()) app.listen(3000, () => { console.log(`Server port is 3000.`) }) If you like, you can follow the official account :Touch the front end,2021 Study and make progress together . - Import file
token.jsfile
边栏推荐
- Enterprise security attack surface analysis tool
- Abstract factory pattern
- What is browser fingerprint recognition?
- Data acquisition and transmission instrument reservoir dam safety monitoring
- During JMeter pressure measurement, time_ The number of requests does not go up due to many waits. The problem is solved
- [go] runtime package for concurrent programming and its common methods
- Tencent blue whale Zhiyun community version v6.0.3 was officially released together with the container management platform!
- Kubernetes 1.20.5 setting up Sentinel
- A survey on dynamic neural networks for natural language processing, University of California
- Cause analysis of the failure of web page live broadcast on demand RTMP streaming platform easydss streaming live broadcast
猜你喜欢

ZOJ - 4104 sequence in the pocket

Ps\ai and other design software pondering notes
Advanced programmers must know and master. This article explains in detail the principle of MySQL master-slave synchronization

Applet wxss
![[leetcode108] convert an ordered array into a binary search tree (medium order traversal)](/img/e1/0fac59a531040d74fd7531e2840eb5.jpg)
[leetcode108] convert an ordered array into a binary search tree (medium order traversal)

Ui- first lesson

C. K-th not divisible by n (Mathematics + thinking) codeforces round 640 (Div. 4)

There are potential safety hazards Land Rover recalls some hybrid vehicles

C. Three displays codeforces round 485 (Div. 2)
MySQL進階系列:鎖-InnoDB中鎖的情况
随机推荐
A troubleshooting of golang memory leak
Druid architecture and Implementation
What is a reptile
Factory mode
Regular expression learning artifact!
Page scrolling effect library, a little skinny
Don't let [mana] destroy your code!
What can Lu yuanjiu Jiao buy?
Coding's first closed door meeting on financial technology exchange was successfully held
D. Solve the maze (thinking +bfs) codeforces round 648 (Div. 2)
2021 devopsdays Tokyo Station ends perfectly | coding experts are invited to share the latest technical information
Cloud + community [play with Tencent cloud] video solicitation activity winners announced
What is the difference between optical fiber jumper and copper wire
Nonholonomic constrained robot
What is the difference between get and post? After reading it, you won't be confused and forced, and you won't have to fight with your friends anymore
A survey on model compression for natural language processing (NLP model compression overview)
Mathematics in machine learning -- point estimation (IV): maximum posteriori probability (map)
ZOJ - 4104 sequence in the pocket
Transpose convolution learning notes
Is Shanjin futures safe? What are the procedures for opening futures accounts? How to reduce the futures commission?