快速上手
zKing 2018-11-28 Koa
摘要
Koa 是 node.js 的一个web框架,小巧且精美
# 事先准备
cnpm install nodemon -D
- 原因:使用
nodemon
是为了不浪费时间去重启服务 - 用法:直接使用 nodemon 代替 node 就可以简单进行使用,当然也可以自己定义配置文件。详情请点击 这里
# 实例
npm init [project]
cnpm install koa -S
// 在koa2中,我们导入的是一个class,因此用大写的Koa表示:
const Koa = require("koa");
const app = new Koa();
app.use(async (ctx, next) => {
const ms = new Date().getTime();
console.log(`Time:${ms}ms`);
await next();
})
app.use(async (ctx,next)=>{
console.log("test");
await next();
});
// 每收到一个http请求,koa就会调用通过app.use()注册的async函数,并传入ctx和next参数。
app.use(async (ctx, next) => {
ctx.type = "text/html";
ctx.body = "<h2>hello world!</h2>";
//必须使用 await 才能使用下一个 async 函数
// await next();
});
app.use(async (ctx,next)=>{
console.log("test2");
await next();
});
app.listen(3000, () => {
console.log("http://localhost:3000");
});
结果:
http://localhost:3000
Time:1541052166660ms
test