let Koa = require('koa');
let router = require('koa-router')();
let bodyParser = require('koa-bodyparser');
let app = new Koa();
// 異步函數
app.use(async (ctx,next)=>{
console.log(`${ctx.request.method}~~~~${ctx.request.url}`);
await next();
});
app.use(async (ctx,next)=>{
let 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.response.type = 'text/html';
ctx.response.body = '<h1>Hello wrod!!!</h1>'
});
// 接口請求(辦法愚蠢)
app.use(async (ctx, next) => {
if (ctx.request.path === '/') {
ctx.response.type = 'text/html'
ctx.response.body = 'index page !!!!!!!!!'
}else{
await next();
}
});
app.use(async (ctx, next) => {
if (ctx.request.path === '/list') {
ctx.response.type = 'text/html'
ctx.response.body = '<ul><li>1</li><li>2</li><li>3</li></ul>'
} else {
await next();
}
});
app.use(async (ctx, next) => {
if (ctx.request.path === '/error') {
ctx.response.type = 'text/html'
ctx.response.body = 'notfund 404 哥們你找錯人了吧'
} else {
await next();
}
});
// 接口請求 (路由)router
app.use(async (ctx, next) => {
console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
await next();
});
router.get('/',async (ctx,next) =>{
ctx.response.body = '<h1>Index</h1>';
});
router.get('/hello/:name', async (ctx, next) => {
var name = ctx.params.name;
ctx.response.body = `<h1>Hello, ${name}!</h1>`
});
// 模擬登錄接口
// bodyParser 解析post數據
app.use(bodyParser());
router.get('/', async (ctx, next) => {
ctx.response.body = `<h1>Index</h1>
<form action="/signin" method="post">
<p>Name: <input name="name" value="koa"></p>
<p>Password: <input name="password" type="password"></p>
<p><input type="submit" value="Submit"></p>
</form>`;
});
router.post('/signin',async (ctx,next) => {
var name = ctx.request.body.name || '',
password = ctx.request.body.password || '';
console.log(`signin with name: ${name}, password: ${password}`);
if (name === 'koa' && password === '12345') {
ctx.response.body = `<h1>Welcome, ${name}!</h1>`;
} else {
ctx.response.body = `<h1>Login failed!</h1>
<p><a href="/">Try again</a></p>`;
}
});
app.use(router.routes());
app.listen(9696);
console.log('app started at port 3000...')