字数:1118,预计阅读时间:6min
Node.js 中请求的处理讨论 Koa 中间件前,先看原生 Node.js 中是如何创建 server 和处理请求的。 node_server.js const http = require("http");const PORT = 3000;const server = http.createServer((req, res) => { res.end("hello world!");});server.listen(PORT);console.log(`server started at http://localhost:${PORT}`); Koa 中请求的处理Koa 也是通过上面的 listen(...args) { debug('listen');+ const server = http.createServer(this.callback()); return server.listen(...args); } Koa 中的 hello world: server.js const Koa = require("koa");const app = new Koa();app.use(async ctx => { ctx.body = "Hello World";});app.listen(3000); Koa 中,涉及到对请求返回处理都是通过中间件完成的,像上面为样,返回页面一个 |