在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:ruanyf/koa-demos开源软件地址:https://github.com/ruanyf/koa-demos开源编程语言:开源软件介绍:A collection of simple demos of Koa, a web application framework for Node. How to useFirst of all, check your Node version. $ node -v
v8.0.0 Koa requires node v7.6.0+. If your version is older than that, upgrade Node first. Then clone the repo (or download zip file). $ git clone [email protected]:ruanyf/koa-demos.git Install the dependencies. $ cd koa-demos
$ npm install Now play with the source files under the demos directory. Index
Demo01: start a serverStarting a server with Koa is very easy. Only 3 lines. // demos/01.js
const Koa = require('koa');
const app = new Koa();
app.listen(3000); Run the demo. $ node demos/01.js Visit http://127.0.0.1:3000 . You should see nothing but 'Not Found' in the page, since we haven't add any content. Demo02: Hello WorldKoa provides a Context object encapsulating HTTP request and response.
// demos/02.js
const Koa = require('koa');
const app = new Koa();
const main = ctx => {
ctx.response.body = 'Hello World';
};
app.use(main);
app.listen(3000); Run the demo. $ node demos/02.js Visit http://127.0.0.1:3000 . Now you should see 'Hello World' in the page. Demo03: response type
// demos/03.js
const Koa = require('koa');
const app = new Koa();
const main = ctx => {
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';
}
};
app.use(main);
app.listen(3000); Run the demo. $ node demos/03.js Visit http://127.0.0.1:3000 . What you see depends on the Demo04: use a templateA template file could be used as the response sending to the client. // demos/04.js
const fs = require('fs');
const Koa = require('koa');
const app = new Koa();
const main = ctx => {
ctx.response.type = 'html';
ctx.response.body = fs.createReadStream('./demos/template.html');
};
app.use(main);
app.listen(3000); Run the demo. $ node demos/04.js Visit http://127.0.0.1:3000 . You will see the content of the template file. Demo05: simple router
// demos/05.js
const Koa = require('koa');
const app = new Koa();
const main = ctx => {
if (ctx.request.path !== '/') {
ctx.response.type = 'html';
ctx.response.body = '<a href="/">Index Page</a>';
} else {
ctx.response.body = 'Hello World';
}
};
app.use(main);
app.listen(3000); Run the demo. $ node demos/05.js Visit http://127.0.0.1:3000/about . You could click the link to the Index page. Demo06: koa-route
// demos/06.js
const Koa = require('koa');
const route = require('koa-route');
const app = new Koa();
const about = ctx => {
ctx.response.type = 'html';
ctx.response.body = '<a href="/">Index Page</a>';
};
const main = ctx => {
ctx.response.body = 'Hello World';
};
app.use(route.get('/', main));
app.use(route.get('/about', about));
app.listen(3000); Run the demo. $ node demos/06.js Visit http://127.0.0.1:3000/about . You could click the link to the Index page. Demo07: loggerLogging is easy. Adding a line into the // demos/07.js
const Koa = require('koa');
const app = new Koa();
const main = ctx => {
console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
ctx.response.body = 'Hello World';
};
app.use(main);
app.listen(3000); Run the demo. $ node demos/07.js Visit http://127.0.0.1:3000 . You will see the logging info in console. Demo08: middlewareThe logger in the previous demo could be taken out as a separate function which we call it a middleware. Because a middleware is like a middle layer between HTTP request and HTTP response to process the data. // demos/08.js
const Koa = require('koa');
const app = new Koa();
const logger = (ctx, next) => {
console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
next();
}
const main = ctx => {
ctx.response.body = 'Hello World';
};
app.use(logger);
app.use(main);
app.listen(3000); Each middleware receives a Koa Context object and a
Run the demo. $ node demos/08.js Visit http://127.0.0.1:3000 . You will see the logging info in console. Demo09: middleware stackMulti middlewares form a middle stack. The most outer middleware is executed first, then passes the execution to the next middleware. And the most inner middleware is executed last, then returns the execution to the previous middleware. It is just like a first-in-last-out stack. // demos/09.js
const Koa = require('koa');
const app = new Koa();
const one = (ctx, next) => {
console.log('>> one');
next();
console.log('<< one');
}
const two = (ctx, next) => {
console.log('>> two');
next();
console.log('<< two');
}
const three = (ctx, next) => {
console.log('>> three');
next();
console.log('<< three');
}
app.use(one);
app.use(two);
app.use(three);
app.listen(3000); Run the demo. $ node demos/09.js Visit http://127.0.0.1:3000 . You will see the following result in console. >> one
>> two
>> three
<< three
<< two
<< one As a exercise, commenting the line of Demo10: async middlewareIf there are async operations in a middleware, you have to use async middleware, i.e. use a async function as middleware. const fs = require('fs.promised');
const Koa = require('koa');
const app = new Koa();
const main = async function (ctx, next) {
ctx.response.type = 'html';
ctx.response.body = await fs.readFile('./demos/template.html', 'utf8');
};
app.use(main);
app.listen(3000); In above codes, Run the demo. $ node demos/10.js Visit http://127.0.0.1:3000 . You will see the content of the template file. Demo11: compose multi middlewares
// demos/11.js
const Koa = require('koa');
const compose = require('koa-compose');
const app = new Koa();
const logger = (ctx, next) => {
console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
next();
}
const main = ctx => {
ctx.response.body = 'Hello World';
};
const middlewares = compose([logger, main]);
app.use(middlewares);
app.listen(3000); Run the demo. $ node demos/11.js Visit http://127.0.0.1:3000 . You will see the logging info in console. Demo12: static assets
// demos/12.js
const Koa = require('koa');
const app = new Koa();
const path = require('path');
const serve = require('koa-static');
const main = serve(path.join(__dirname));
app.use(main);
app.listen(3000); Run the demo. $ node demos/12.js Visit http://127.0.0.1:3000/12.js . you will see the above code. Demo13: response redirecting
// demos/13.js
const Koa = require('koa');
const route = require('koa-route');
const app = new Koa();
const redirect = ctx => {
ctx.response.redirect('/');
ctx.response.body = '<a href="/">Index Page</a>';
};
const main = ctx => {
ctx.response.body = 'Hello World';
};
app.use(route.get('/', main));
app.use(route.get('/redirect', redirect));
app.use(main);
app.listen(3000); Run the demo. $ node demos/13.js Visit http://127.0.0.1:3000/redirect. The browser will be redirected to the root path. Demo14: 500 error
// demos/14.js
const Koa = require('koa');
const app = new Koa();
const main = ctx => {
ctx.throw(500);
};
app.use(main);
app.listen(3000); Run the demo. $ node demos/14.js visit http://127.0.0.1:3000. You will see a 500 error page of "Internal Server Error". |