Table of Contents
1 简单搭建http server
const http = require('http');
const url = require('url');
const port = 7799;
const host = '127.0.0.1';
const srv = http.createServer(function (req, res) {
let pathname = url.parse(req.url).pathname;
if (pathname === '/index.html') {
res.end('hello world');
} else {
res.statusCode = 404;
res.end('not found');
}
});
srv.listen(port, host, function () {
console.log(`server is running at http://${host}:${port}`);
});
2 搭建的http server
const port = 7799;
const host = '127.0.0.1';
const koa = require('koa');
const app = new koa();
app.listen(port, host, () => {
console.log(`server running at http://${host}:${port}`);
});
2.1 添加了简单的返回内容
const port = 7799;
const host = '127.0.0.1';
const koa = require('koa');
const app = new koa();
app.use(async (ctx, next) => {
await next();
ctx.type = 'text/html';
// ctx.type = 'text/plain';
ctx.body = '<h1>hello, world</h1>'
});
app.listen(port, host, () => {
console.log(`server running at http://${host}:${port}`);
});
2.2 抛出错误
const port = 7799;
const host = '127.0.0.1';
const koa = require('koa');
const app = new koa();
app.use(async (ctx, next) => {
await next();
// ctx.status = 404;
ctx.type = 'text/html';
ctx.type = 'text/plain';
ctx.body = '<h1>hello, world</h1>';
ctx.throw(500);
});
app.listen(port, host, () => {
console.log(`server running at http://${host}:${port}`);
});
2.3 中间件传递数据(state)
const port = 7799;
const host = '127.0.0.1';
const koa = require('koa');
const app = new koa();
app.use(async (ctx, next) => {
ctx.type = 'text/html';
ctx.body = '<h1>hello world</h1>';
ctx.state.name = '<h2>Oh yah</h2>'
await next();
});
app.use(async (ctx, next) => {
ctx.body = ctx.state.name + ctx.body;
await next();
});
app.listen(port, host, () => {
console.log(`server running at http://${host}:${port}`);
});
2.4 中间件代码执行过程
像穿过网一样,逐层进入,在一层层返回(栈结构)
2.4.1 执行代码
const port = 7799;
const host = '127.0.0.1';
const koa = require('koa');
const app = new koa();
app.use(async (ctx, next) => {
console.log('1 before')
await next();
console.log('1 finish')
});
app.use(async (ctx, next) => {
console.log('2 before')
await next();
console.log('2 finish')
});
app.use(async (ctx, next) => {
console.log('3 before')
await next();
console.log('3 finish')
});
app.listen(port, host, () => {
console.log(`server running at http://${host}:${port}`);
});
2.4.2 访问输出的代码
1 before 2 before 3 before 3 finish 2 finish 1 finish
2.4.3 多个中间件合成一个
const port = 7799;
const host = '127.0.0.1';
const koa = require('koa');
const app = new koa();
const compose = require('koa-compose');
app.use(async (ctx, next) => {
console.log('org before')
await next();
console.log('org finish')
});
const all = compose([
async (ctx, next) => {
console.log('1 before')
await next();
console.log('1 finish')
},
async (ctx, next) => {
console.log('2 before')
await next();
console.log('2 finish')
},
async (ctx, next) => {
console.log('3 before')
await next();
console.log('3 finish')
}]);
app.use(all);
app.listen(port, host, () => {
console.log(`server running at http://${host}:${port}`);
});
org before 1 before 2 before 3 before 3 finish 2 finish 1 finish org finish
2.4.4 测试响应耗时的列子
const port = 7799;
const host = '127.0.0.1';
const koa = require('koa');
const app = new koa();
app.use(async (ctx, next) => {
ctx.state.time = {
beg: new Date().getTime(),
end: ''
};
await next();
ctx.state.time.end = new Date().getTime();
console.log('ms:', ctx.state.time.end - ctx.state.time.beg);
});
app.use(() => {
for(let i = 0; i < 1000000000; ++i){
++i;
}
});
app.listen(port, host, () => {
console.log(`server running at http://${host}:${port}`);
});
3 一些中间件
3.1 koa-body
解析form-data数据
const port = 7799;
const host = '192.168.0.103';
const koa = require('koa');
const app = new koa();
const koaBody = require('koa-body');
app.use(koaBody({//还有很多配置参数
multipart : true //解决postman请求body一直为空
}));
app.use((ctx) => {
ctx.type = 'html';
let method = ctx.method.toLowerCase();
if (method === 'get') {
ctx.body = `
<h2>登录</h2>
<form method="post" action="/">
<div>
<span>用户名</span>
<input name="user"/>
</div>
<div>
<span>密码</span>
<input name="pwd"/>
</div>
<button type="submit">提交</button>
</form>
`;
} else if (method === 'post') {
let data = ctx.request.body;
console.log(data)
// console.log(ctx.req)
}
});
app.listen(port, host, () => {
console.log(`server running at http://${host}:${port}`);
});
3.2 koa-router
const port = 7799;
const host = '192.168.0.103';
const koa = require('koa');
const app = new koa();
const Body = require('koa-body');
const Router = require('koa-router');
const router = new Router();
app
.use(Body({//还有很多配置参数
multipart: true //解决postman请求body一直为空
}))
.use(router.routes())
.use(router.allowedMethods());
let page = `
<h2>登录</h2>
<form method="post" action="/">
<div>
<span>用户名</span>
<input name="user"/>
</div>
<div>
<span>密码</span>
<input name="pwd"/>
</div>
<button type="submit">提交</button>
</form>
`;
router
.get('/', (ctx) => {
ctx.type = 'html';
ctx.body = page;
})
.post('/', (ctx) => {
console.log(ctx.request.body);
ctx.type = 'html';
ctx.body = '<h1>提交成功</h1>'
});
app.listen(port, host, () => {
console.log(`server running at http://${host}:${port}`);
});
3.3 koa-views 和 koa-static
用于请求静态资源,中间件引入顺序很重要,否则可能出现想不到的情况(很操蛋)
3.3.1 目录结构
. ├── app.js ├── static └── views └── index.html
3.3.2 ./views/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>登录</h2>
<form method="post" action="/">
<div>
<span>用户名</span>
<input placeholder="请输入姓名" type="text" name="user" />
</div>
<div>
<span>密码</span>
<input placeholder="请输入密码" type="password" name="pwd"/>
</div>
<button type="submit">提交</button>
</form>
</body>
</html>
3.3.3 ./app.js
const port = 7799;
const host = '192.168.0.103';
const koa = require('koa');
const app = new koa();
const Body = require('koa-body');
const Router = require('koa-router');
const router = new Router();
const view = require('koa-views');
const statics = require('koa-static');
const path = require('path');
app
.use(view(path.join(path.resolve(__dirname), 'views'), {
map: {html: 'ejs'}
}))
.use(statics(path.join(path.resolve(__dirname), 'static')));
router
.get('/', async (ctx) => {
await ctx.render('index');
})
.post('/', (ctx) => {
console.log(ctx.request.body);
ctx.type = 'html';
ctx.body = '<h1>提交成功</h1>'
});
// 放到上边没有正常显示(原因暂时不知道是啥)
app
.use(Body({//还有很多配置参数
multipart: true //解决postman请求body一直为空
}))
.use(router.routes())
.use(router.allowedMethods());
app.listen(port, host, () => {
console.log(`server running at http://${host}:${port}`);
});
Created: 2019-07-02 周二 11:13