初次尝试使用nodejs koajs

 

 

 

 

 1 const fs = require('fs');
 2 const path = require('path');
 3 const Koa = require('koa');
 4 const route = require('koa-route');
 5 const static = require('koa-static');
 6 const app = new Koa();
 7 
 8 const main = ctx => {
 9     /**
10      * 判断页面请求类型 Accept 返回相应格式内容
11      */
12     if (ctx.request.accepts('xml')) {
13         ctx.response.type = 'xml';
14         ctx.response.body = '<data>Hello World</data>';
15     } else if (ctx.request.accepts('json')) {
16         ctx.response.type = 'json';
17         ctx.response.body = { data: 'Hello World' };
18     } else if (ctx.request.accepts('html')) {
19         ctx.response.type = 'html';
20         ctx.response.body = '<p>Hello World</p>';
21     } else {
22         ctx.response.type = 'text';
23         ctx.response.body = 'Hello World';
24     }
25 }
26 /**
27  * 原生路由
28  * @param {*} ctx 
29  */
30 const main_1 = ctx => {
31     if (ctx.request.path !== '/') {
32         ctx.response.type = 'html';
33         ctx.response.body = fs.createReadStream('./view/index.html');
34     } else {
35         ctx.response.body = 'Hello World';
36     }
37 };
38 // app.use(route);
39 
40 /**
41  * 日志打印-中间件
42  * @param {*} ctx 
43  * @param {*} next 
44  */
45 const logger = (ctx, next) => {
46     console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
47     next();
48 };
49 app.use(logger);
50 /**
51  * koa-route 路由使用
52  */
53 const index = ctx => {
54     ctx.response.type = 'html';
55     ctx.response.body = fs.createReadStream('./view/index.html');
56 };
57 const about = ctx => {
58     ctx.response.type = 'html';
59     ctx.response.body = fs.createReadStream('./view/about.html');
60 };
61 app.use(route.get('/', index));
62 app.use(route.get('/about', about));
63 /**
64  * 重定向
65  */
66 app.use(route.get('/redirect', about));
67 /**
68  * 静态文件访问
69  */
70 app.use(static(path.join(__dirname)));
71 
72 
73 app.listen(3000);

 

posted @ 2018-04-14 15:49  何以孑然  阅读(454)  评论(0)    收藏  举报