// 使用koa框架
const Koa = require('koa');
// koa-route模块
const route = require('koa-route');
const path = require('path');
// 处理静态文件
// 如果网站提供静态资源(图片、字体、样式表、脚本......)
// koa-static模块封装了这部分的请求。
const serve = require('koa-static');
// 提供脚本资源
const main = serve(path.join(__dirname));
// 中间件合成
const compose = require('koa-compose');
const app = new Koa();
const main = ctx => {
// HTTP Response 的类型
if (ctx.request.accepts('xml')) {
ctx.response.type = 'xml';
ctx.response.body = '<data>Hello World</data>';
} else if (ctx.request.accepts('json')) {
ctx.response.type = 'json';
ctx.response.body = { data: 'Hello World' };
} else if (ctx.request.accepts('html')) {
ctx.response.type = 'html';
ctx.response.body = '<p>Hello World</p>';
} else {
ctx.response.type = 'text';
ctx.response.body = 'Hello World';
}
// 原生路由写法
if (ctx.request.path !== '/') {
ctx.response.type = 'html';
ctx.response.body = '<a href="/">Index Page</a>';
} else {
ctx.response.body = 'Hello World';
}
};
// koa-route模块写法
const about = ctx => {
ctx.response.type = 'html';
ctx.response.body = '<a href="/">About Page</a>';
};
// 重定向
const redirect = ctx => {
ctx.response.redirect('/');
ctx.response.body = '<a href="/">Index Page</a>';
};
// 打印日志
const main = ctx => {
console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
ctx.response.body = 'Hello World';
};
// logger函数就是中间件,因为它处在 HTTP Request 和 HTTP Response 中间,用来实现某种中间功能。
// 多个中间件会形成一个栈结构(middle stack),以"先进后出"(first-in-last-out)的顺序执行。
const logger = (ctx, next) => {
console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
next();
}
// 异步中间件
const main = async function (ctx, next) {
ctx.response.type = 'html';
ctx.response.body = await fs.readFile('./demos/template.html', 'utf8');
};
// 中间件合成
const middlewares = compose([logger, main]);
// 原生路由写法
app.use(main);
// koa-route路由写法
app.use(route.get('/about', about));
app.use(route.get('/redirect', redirect));
app.use(middlewares);
app.listen(3000);
网友评论