首页 Node Koa.js框架

测试配置


系统平台:Windows 10
Node版本:node-v18.16.1-win-x64
Koa版本:2.14.2(需要 node v7.6.0或更高版本)
编辑工具:VS code

Koa.js框架安装


安装框架:   
npm install koa@2.14.2

简单的服务器:
var koa = require("koa");
var app = new koa();
app.listen(8080);

app.use(async ctx => {
    ctx.body = "www.liboke.cn";  //响应文本
});    

app相关


属性 描述
keys 设置签名cookie密钥
context 向ctx添加属性、方法
   

方法 描述
listen() 创建服务器,监听端口
use() 添加指定的中间件
callback() 返回一个http.createServer()使用的回调函数
on() 绑定事件
   

ctx相关


属性/方法

描述

测试地址:http://localhost:8080/?name=liboke

req 或 request request 请求对象,使用原生node方法
res 或 response response 响应对象,使用原生node方法
state  
app 应用实例引用
   
header 获取、设置,请求头对象
headers 获取、设置,请求头对象,等价request.header
method

获取、设置,请求方法

返回值:GET、POST

length 返回,请求内容长度
url

获取、设置,请求url地址

返回值:/?name=liboke

URL

获取,请求地址对象

返回值:

URL {
  href: 'http://localhost:8080/?name=liboke',
  origin: 'http://localhost:8080',
  protocol: 'http:',
  username: '',
  password: '',
  host: 'localhost:8080',
  hostname: 'localhost',
  port: '8080',
  pathname: '/',
  search: '?name=liboke',
  searchParams: URLSearchParams { 'name' => 'liboke' },
  hash: ''
}

originalUrl

获取,请求原始地址

返回值:/?name=liboke

origin

获取,请求原始地址, 包含 protocol 和 host

返回值:http://localhost:8080

href

获取完整的请求URL

返回值:http://localhost:8080/?name=liboke

path

获取、设置,请求路径查询字符

返回值:/

query

获取,设置,参数字段,返回对象

返回值:[Object: null prototype] { name: 'liboke' }

querystring

获取、设置,参数字段,返回字符串,不包含"?"

返回值:name=liboke

host

获取,地址+端口

返回值:localhost:8080

hostname

获取,地址

返回值:localhost

fresh

判断,请求缓存内容没有发生变化

返回值:true、false

stale 与 fresh 相反
socket 返回请求的socket
protocol 返回,请求协议,"https" 或者 "http"
secure 检查请求是否通过 TLS 发送
ip 请求远程地址
ips  
subdomains 以数组形式返回子域名
   
body 设置,获取,响应文本,HTML
status 获取、设置,响应状态,默认404
message 获取,响应状态信息
length 获取、设置,Content-Length
type 获取、设置,Content-Type
headerSent 检查 response header 是否已经发送
lastModified 如果存在 Last-Modified,则以 Date 的形式返回
etag  
   
is() 判断,Content-Type是否指定值
redirect()

重定向 url

例:ctx.redirect('http://www.liboke.cn');

accepts()  
acceptsEncodings()  
acceptsCharsets()  
acceptsLanguages()  
get()

获取 response header 中字段值

例:var CacheControl = ctx.get('Cache-Control');

set()

设置 response header 字段值

例:ctx.set('Cache-Control', 'no-cache');

   
redirect()  
attachment()  
append()

添加 response header 字段

例:ctx.append('Link', '<http://127.0.0.1/>');

remove() 移除 response header 中字段
   
cookies.get() 获得 cookie 中名为 name 的值
cookies.set() 设置 cookie 中名为 name 的值