当前位置:网站首页>Introduction to koa (III) koa routing
Introduction to koa (III) koa routing
2022-06-24 16:38:00 【Uncertainty】
stay Koa Application , You usually use koa-router modular , Provide support for routing . Then why do I need routing ? Friends who do front and back-end separation development have all met , When docking interfaces, the background will provide an address , Request this address , The corresponding data processing can be realized by transmitting the corresponding parameters . You can put this An interface is understood as the address of a route .
1 koa-router Use
1.1 Installation and introduction
npm i koa-router --savenewly buildrouter.jsfile const Koa = require('koa') const Router = require('koa-router') const app = new Koa() const router = new Router() router.get('/', ctx => { ctx.body = ' Hello , Uncertainty of measurement ' }) // Registered routing app.use(router.routes()) // Auto enrichment response Corresponding head , When the response state is not set (status) Automatically set when , Set at the end of all routing middleware ( overall situation , recommend ), You can also set a specific route ( Local ), for example :router.get('/index', router.allowedMethods()); This is equivalent to when visiting /index It's only set up when app.use(router.allowedMethods()) app.listen(3000, () => { console.log(' monitor 3000 port ') }) Add, delete, and change the route of the query // To obtain a list of , Returns an array of router.get('/', ctx => { ctx.body = [] }) // according to id Get an item , Returns the object router.get('/:id', ctx => { ctx.body = {} }) // Create a new item router.post('/', ctx => { ctx.body = {} }) // according to id Update an item router.put('/:id', ctx => { ctx.body = {} }) // according to id Delete an item router.delete('/:id', ctx => { ctx.body = {} })koa-router( Support basic commonhttpMethod ('HEAD','OPTIONS','GET','PUT','PATCH','POST','DELETE'), The obscure request method will return501Status code )- If you want to add logical judgment before routing , For example, do you have permission to access , Middleware can be inserted into the route // Define middleware const auth = async (ctx, next) => { if (ctx.url !== '/users') { ctx.throw(401) } await next() } // Inject router.post('/users', auth, ctx => { ctx.body = ctx.request.body })
1.2 Parameters to obtain
getTo obtain parameters (ctx.paramsperhapsctx.request.params)// Get a single parameter router.get('/:id', ctx => { ctx.body = ctx.params }) // Get multiple parameters router.get('/:id/:age', ctx => { ctx.body = ctx.request.params })
postTo obtain parameters (ctx.request.body) Third party middleware is required to obtain parameters ,koa-bodyparser:npm i koa-bodyparser --saveconst Koa = require('koa') const Router = require('koa-router') const bodyParser = require('koa-bodyparser') const app = new Koa() const router = new Router() router.post('/', ctx => { ctx.body = ctx.request.body }) // Put it in front of the route app.use(bodyParser()) app.use(router.routes()) app.use(router.allowedMethods()) app.listen(3000, () => { console.log(' monitor 3000 port ') })
2 Route encapsulation
It is impossible for our development projects to write routes in index.js In the entry file , You need to use a separate routing folder to manage , Just import one in the entry file .
- Root creation
app/routes/home.jsconst Router = require('koa-router') const router = new Router() router.get('/', (ctx) => { ctx.body = ' home page ' }) module.exports = routerconst Router = require('koa-router') // ** Configure routing prefix ** const router = new Router({ prefix: '/users' }) router.get('/', (ctx) => { ctx.body = ' User list ' }) router.get('/:id', ctx => { ctx.body = ` user id:${ctx.params.id}` }) module.exports = router Because there are many interfaces for routing in a project , It can't be at the entranceindex.jsEach of them should introduce , Therefore, all routes need to be handled , In this way, you only need to import one in the entry file - establish
app/routes/users.js - establish
app/routers/index.jsconst fs = require('fs') module.exports = app => { // Read all files in the current directory fs.readdirSync(__dirname).forEach(file => { // Remove inductive `index.js` file , All others must be registered to `app` in if (file === 'index.js') return const router = require(`./${file}`) app.use(router.routes()).use(router.allowedMethods()) }) }... // introduce const routing = require('./routes') ... // Use routing(app) ... - stay
app/index.jsIntroduction in
3 Using the controller
We are now processing the data ( Although the data has not been written yet , Write dead ) Together with routing , This is not convenient for maintenance , And the later data processing is complicated , It will appear that the routing file is very bloated , We should separate routing files from data processing .
- establish
app/controllers/home.jsclass HomeCtl { index(ctx) { ctx.body = ' This is the home page ' } } module.exports = new HomeCtl() - modify
app/routes/home.jsconst Router = require('koa-router') const router = new Router() // const { index } = require('../controllers/home') router.get('/', index) module.exports = router - establish
app/controllers/users.jsclass UsersCtl { async find(ctx) { // Operating the database must await ctx.body = ' User list ' } async findById(ctx) { ctx.body = ` user id:${ctx.params.id}` } } module.exports = new UsersCtl
attach : Onion model
Through the introduction of the previous two sections, I believe that you have made a good understanding of Koa Understand the implementation mechanism of , In especial await next() After execution, the middleware will return to continue to execute the unexecuted logic , Without feeling the author's ingenious design ideas . Let's briefly understand the implementation idea , The core code is koa-componse in , There's not much code , Let's simply learn :
function compose(middleware) {
return function(context) {
// We actually just returned the first item of middleware , But the first item will execute recursively
return dispatch(0);
function dispatch(i) {
let fn = middleware[i];
try {
// Every time you execute fn Function time ,fn Contained in the next function (dispatch(i + 1)), So we have to execute first next Code , Go back and execute the following code of the middleware
return Promise.resolve(fn(context, dispatch.bind(null, i + 1));
} catch (err) {
return Promise.reject(err);
}
}
};
}- Define the middleware array to be tested const middleware = [ async (ctx, next) => { console.log("1"); await next(); console.log("3"); }, async (ctx, next) => { console.log("2"); } ]; We can see , Execute in the middleware
await next(), It's actually execution :await dispatch.bind(null, i + 1). So it looks like , The current middleware will stop its logic , Process the next middleware first . Because of everydispatch, All return to the newPromise. thereforeasyncWill waitPromiseWhen the state changes, you can go back and continue to execute your own logic . - Simply write a method to execute according to the onion model ( Don't consider the online articles , Just pure execution )let middlewares = [ async (next) => { console.log(1) await next() console.log(3) }, async (next) => { console.log(2) await next() }, async (next) => { console.log('test') } ] function componse() { return dispatch(0) async function dispatch(i) { let fn = middlewares[i] await fn(dispatch.bind(null, i + 1)) } } componse()
In the next article, we will learn database The operation of , If it helps you , Welcome to pay attention ! Thank you for reading !
边栏推荐
- What is a framework?
- Finite element simulation in design
- 50 growers | closed door meeting of marketing circle of friends ス gathering Magic City thinking collision to help enterprise marketing growth
- What is the difference between optical fiber jumper and copper wire
- What is a server
- AI video structured intelligent security platform easycvr intelligent security monitoring scheme for protecting community residents
- National standard gb28181 protocol video platform easygbs alarm reporting function adds video alarm reporting and video recording
- Some adventurer hybrid versions with potential safety hazards will be recalled
- MySQL日期时间戳转换
- MySQL Advanced Series: locks - locks in InnoDB
猜你喜欢

C. K-th Not Divisible by n(数学+思维) Codeforces Round #640 (Div. 4)

Ps\ai and other design software pondering notes

A survey of training on graphs: taxonomy, methods, and Applications

ZOJ - 4104 sequence in the pocket

A survey on dynamic neural networks for natural language processing, University of California

Cognition and difference of service number, subscription number, applet and enterprise number (enterprise wechat)

Ui- first lesson

Applet - use of template

B. Ternary Sequence(思维+贪心)Codeforces Round #665 (Div. 2)

B. Terry sequence (thinking + greed) codeforces round 665 (Div. 2)
随机推荐
[go] concurrent programming channel
C. Three displays codeforces round 485 (Div. 2)
The million bonus competition is about to start, and Ti-One will be upgraded to help you win the championship!
[golang] Introduction to golang (I) establishment of running environment
找出隐形资产--利用Hosts碰撞突破边界
How to pop up an alarm through the national standard gb28181 protocol video platform easygbs for mobile detection / perimeter intrusion detection video recording
Enterprise security attack surface analysis tool
A survey of training on graphs: taxonomy, methods, and Applications
Greenplum role-based fine-grained permission control
[go] runtime package for concurrent programming and its common methods
Mathematics in machine learning -- point estimation (IV): maximum posteriori probability (map)
Advanced programmers must know and master. This article explains in detail the principle of MySQL master-slave synchronization
Use Google search like a professional
Global and Chinese market of computer protective film 2022-2028: Research Report on technology, participants, trends, market size and share
AI video structured intelligent security platform easycvr realizes intelligent security monitoring scheme for procuratorate building
A troubleshooting of golang memory leak
How do HPE servers make RAID5 arrays? Teach you step by step today!
Heavy release! Tencent cloud ASW workflow, visual orchestration cloud service
Yuanqi forest started from 0 sugar and fell at 0 sugar
A set of very good H3C and Tianrongxin Internet cutover scheme templates, with word document download