markdown [Koa路由]如何管道koa步骤和路由器#koa #koarouter#node.js #javascript

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown [Koa路由]如何管道koa步骤和路由器#koa #koarouter#node.js #javascript相关的知识,希望对你有一定的参考价值。

'use strict';
const Koa = require('koa');
const KoaBodyParser = require('koa-bodyparser');
const KoaRouter = require('koa-router');

const app = new Koa();
const router = new KoaRouter();

app
.use(KoaBodyParser())

// x-response-time
app.use(async (ctx, next) => {
	console.log('first');
	const start = Date.now();
	await next();
	const ms = Date.now() - start;
	ctx.set('X-Response-Time', `${ms}ms`);
	console.log(ctx);
});

// logger
app.use(async (ctx, next) => {
	console.log('second');
	const start = Date.now();
	await next();
	const ms = Date.now() - start;
	console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});

// response
app.use(async (ctx, next) => {
	console.log('third');
	ctx.body = 'Hello World';
	await next();
});

// router
router.get('/', (ctx, next) => {
	// ctx.router available
	console.log('router working');
	next();
});

app
.use(router.routes())
.use(router.allowedMethods());

const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, () => {
	console.log(`Server listening on port ${PORT}.`);
});
# Koa

Uses middleware pattern.  
Each time we use app.use we add an other middleware function.  

> ctx - The context contains all the information for a signle request and the response object aswell.


> next - Calls the next middleware.

The order is sequential.  
The router methods order depends on where we add: 

```js
app
.use(router.routes())
.use(router.allowedMethods());
```

If its after the "general" methods they run first and then get passed. 

* [Koa](http://koajs.com/)
* [Koa router](https://github.com/alexmingoia/koa-router)
* [Koa body parser](https://github.com/koajs/bodyparser)

以上是关于markdown [Koa路由]如何管道koa步骤和路由器#koa #koarouter#node.js #javascript的主要内容,如果未能解决你的问题,请参考以下文章

Koa 路由

node-koa-路由传值

koa2系列教程koa2使用路由中间件

koa使用koa-passport实现路由进入前登录验证

Koa2学习使用koa-router

koa 常用中间件