企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 一、安装 > Koa要求node版本需要在7.6以上,所以使用前先node -v查询当前PC上的node版本。如果版本低于7.6,则需要升级后使用。 ``` # 初始化 mkdir mykoa cd mykoa npm init --yes # 安装 npm i koa ``` ## 二、基本使用 ``` const Koa = require('koa') const app = new Koa() app.listen(3000) ``` ### 2.1、context对象 > Koa 提供一个 Context 对象,表示一次对话的上下文(包括 HTTP 请求和 HTTP 回复)。通过加工这个对象,就可以控制返回给用户的内容。 - ctx.response 代表Http Response - ctx.request 代表Http Requeset ``` # demo.js const Koa = require('koa') const app = new Koa() const main = ctx=>{ ctx.response.body='hello world' } app.use(main) app.listen(3000) # 启动 node demo.js # 浏览 localhost:3000 ``` ### 2.2、Http Response的类型 > koa默认返回的类型为text/plain,如果想返回其他类型的内容,可以先用**request.accepts**判断一下,客户端希望接受什么数据(根据 HTTP Request 的Accept字段),然后使用ctx.response.type指定返回类型。 ``` const Koa = require('koa') const app = new Koa() const main = ctx => { if(ctx.request.accepts('xml')){ ctx.response.type='xml' ctx.response.body='<data>这是一个xml</data>' }else if(ctx.request.accepts('json')){ ctx.response.type = 'json' ctx.response.body={data:'123'} } else if (ctx.request.accepts('html')) { ctx.response.type = 'html' ctx.response.body='<p>了不起???</p>' } else { ctx.response.type = 'text' ctx.response.body='hehe' } } app.use(main) app.listen(3000) # 启动后访问,可以看到响应了xml ``` ### 2.3 网页模板 > 实际开发中,返回给用户的网页往往都写成模板文件。我们可以让 Koa 先读取模板文件,然后将这个模板返回给用户。 ``` const Koa = require('koa') const fs = require('fs') const app = new Koa() const main = ctx => { ctx.response.type = 'html' ctx.response.body=fs.createReadStream('./index.html') } app.use(main) app.listen(3000) ```