【知识整理】Node.js-Koa之路由

一。路由

1.原生路由:通过ctx.request.path可以获取用户请求的路径,实现简单的路由。

const main = ctx =>{
	if(ctx.request.path !== '/'){
		ctx.response.type='html';
		ctx.response.body = '<a href="/">Index</a>';
		return;
	}
	ctx.response.body = 'Hello World';
}   
2.koa-route模块

const route = require('koa-route');
const about = ctx =>{
	ctx.response.type='html';
	ctx.response.body='<a href="/">Index</a>';
};
const main = ctx =>{
	ctx.response.body = 'Hello World';
};
app.use(route.get('/', main));
app.use(route.get('/about'), about)
3.静态资源:如果网站提供静态资源(图片,字体,css,js等),为它们挨个写路由很麻烦。koa-static模块封装可该部分请求。

const path = require('path');
const serve = require('koa-static');
const main = serve(path.join(_dirname));
app.use(main);
4.重定向:ctx.response.redirect()方法可以发出一下302跳转,将用户导向另一个路由。

const redirect = ctx =>{
	ctx.response.redirect('/');
	ctx.response.body = '<a href="/">Index</a>';
}
app.use(route.get('/redirect', redirect));
//访问:http://localhost:3000/redirect,浏览器里会将用户导向根路径
4.中间件栈:多个中间件会形成一个栈结构,以先进后出的顺序执行。
(1)最外层的中间件首先执行
(2)调用next函数,把执行权交给下一个中间件
(3)最内层的中间件最后执行
(4)执行结束后把执行权交回上一层中间件
(5)最外层的中间件收回执行权后,执行next函数后面的代码。

const one = (ctx, next) =>{
	console.log('one');
	next();
	console.log('one');
}
const two = (ctx, next) =>{
	console.log('two');
	next();
	console.log('two');
}
app.use(one);
app.use(two);
//运行结果:
//one
//two
//two
//one
5.异步中间件:如有异步操作,如读取数据库,中间件则应携带async函数

const fs = require('fs');
const Koa = require('koa');
const app = new Koa();
const main = async function(ctx, next){
	ctx.response.type='html';
	ctx.response.body = await fs.readFile(./a.html, 'utf-8');;
}
app..use(main);
app.listen(3000);
//上面的代码,fs.readFile是一个异步操作,必须写成await fs.readFile(),中间件必须写成async
6.中间件的合成:koa-compose模块可将多个中间件合成为一个。
const compose = require('koa-compose');
const logger = (ctx, next) =>{
	console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
	next();
}
conse main = ctx =>{
	ctx.response.body = 'Hello World';
}
const middlewares = compose([logger, main]);
app.use(middlewares);






猜你喜欢

转载自blog.csdn.net/qq_19891827/article/details/78470182
今日推荐