const Koa = require('koa');const app = new Koa();// 1. 中间件的演示// app.use(async (ctx, next) => {// console.log(`${ctx.request.method} ${ctx.request.url}`);// await next();// })// app.use(async (ctx, next) => {// const start = new Date().getTime(); //当前时间// await next();// const ms = new Date().getTime() - start;// console.log(`Time: ${ms}ms`)// })// app.use(async (ctx, next) => {// await next();// ctx.type = 'text/html';// ctx.body = 'Hello, Koa2!';// })// 2. 设置不同的路由演示// app.use(async (ctx, next) => {// if(ctx.url === '/') ctx.body = 'index page'// else await next();// })// app.use(async (ctx, next) => {// if(ctx.url === '/test') ctx.body = 'test page'// else await next();// })// app.use(async (ctx, next) => {// if(ctx.url === '/error') ctx.body = 'error page'// else await next();// })// 3. 使用koa-router 改进2的代码// npm i koa-router// const router = require('koa-router')();// 注意这里是一个函数// app.use(async (ctx, next) => {// console.log(`Process ${ctx.method} ${ctx.url}...`);// await next();// });// router.get('/hello/:name', async (ctx, next) => {// let name = ctx.params.name;// ctx.body = `Hello, ${name} !`// })// router.get('/', async (ctx, next) => {// ctx.body = ` Index `// })// app.use(router.routes());//将router.routes()注册到app//注意,这句话一般是要放到最后的,因为这句话之后的中间件都不会执行。// 4. 使用 koa-router 的 post 请求中间件问题const router = require('koa-router')();const bodyParser = require('koa-bodyparser');// npm i koa-bodyparserapp.use(bodyParser());router.get('/', async (ctx, next) => {ctx.body = ` Index Name: Password: `})router.post('/signin', async (ctx, next) => {let name = ctx.request.body.name || '';let password = ctx.request.body.password || '';console.log(`signin with name: ${name} , password: ${password}`);if(name === 'koa' && password === '12345') {ctx.body = ` Welcome, ${name}`;}else {ctx.body = ` Login failed! Try again `}})app.use(router.routes());app.listen(3000)
Name:
Password:
Try again