Node.js & Koa.js All In One
Node.js & Koa.js All In One
Koa.js
$ nvm install 7
# node.js 7 +
$ nvm install 10
$ npm i koa
$ node ./koa-app.js
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
demos
const Koa = require('koa');
const app = new Koa();
// logger
app.use(async (ctx, next) => {
await next();
const rt = ctx.response.get('X-Response-Time');
console.log(`${ctx.method} ${ctx.url} - ${rt}`);
});
// x-response-time
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
});
// response
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
// var http = require("http");
// //create a server object:
// http
// .createServer(function(req, res) {
// res.write("Hello World!"); //write a response to the client
// res.end(); //end the response
// })
// .listen(8080); //the server object listens on port 8080
const Koa = require("koa");
const app = new Koa();
const log = console.log;
// logger
app.use(async (ctx, next) => {
await next();
// middleware 1, 后执行
const rt = ctx.response.get("X-Response-Time");
log(`\nmiddleware 1, 后执行`, rt);
log(`${ctx.method} ${ctx.url} - ${rt}`);
});
// x-response-time
app.use(async (ctx, next) => {
const start = Date.now();
await next();
// middleware 2, 先执行
const ms = Date.now() - start;
log(`\nmiddleware 2, 先执行`, `${ms}ms`);
ctx.set("X-Response-Time", `${ms}ms`);
});
// response
app.use(async (ctx, next) => {
// log(`response ctx`, ctx);
// await next();
log(`\nmiddleware 0, 最后的 middleware 最先执行`);
ctx.body = "Hello World! <br />powered by koa.js";
});
app.listen(3000);
// app.listen(8080);
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/9765067.html
未经授权禁止转载,违者必究!