Koa 给自己的定位是 HTTP 中间件框架(middleware framework),专注于提供与创建 HTTP 服务器有关的通用方法和属性,本身不捆绑任何中间件,由开源社区根据实际需求开发具体的中间件。
Koa 使用 app.use()方法注册中间件,并按照注入顺序将其添加到 middleware 数组,这些中间件常用于对 HTTP 请求进行加工处理,比如生成缓存、指定代理以及重定向等。
const Koa = require('koa');const app = new Koa();// responseapp.use(ctx => { ctx.body = 'Hello Koa';});app.listen(3000)
Middleware
Koa2 支持以下三种中间件函数:
// common function app.use((ctx, next) => { const start = new Date(); return next().then(() => { const ms = new Date() - start; console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); });});// async functionapp.use(async (ctx, next) => { const start = new Date(); await next(); const ms = new Date() - start; console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);});// generator function.use(co.wrap(function *(ctx, next) { const start = new Date(); yield next(); const ms = new Date() - start; console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);}));
由于 Node.js 尚未支持 async 函数,所以需要使用 Babel 预编译 JS 文件,我的做法是安装依赖 babel-core babel-polyfill babel-preset-es2015 babel-preset-stage-0,然后在真实的入口文件(比如 index.js)前设置一个加载 Babel 的伪入口文件(比如 index.babel.js),将来 Node.js 支持 Async 后删除该文件即可:
require("babel-core/register")({ "presets": [ "es2015", "stage-0" ]});require("babel-polyfill");require('./index.js');
中间件固定接收 (ctx, next)两个参数,如果要传入其他参数,可以对中间件重新打包:
function logger(format) { format = format || ':method ":url"'; return async function (ctx, next) { const str = format .replace(':method', ctx.method) .replace(':url', ctx.url); console.log(str); await next(); };}app.use(logger());app.use(logger(':method :url'));
使用中间件 koa-compose可以合并多个中间件:
const compose = require('koa-compose');async function random(ctx, next) { // ...};async function backwards(ctx, next) { // ...};async function pi(ctx, next) { // ...};const all = compose([random, backwards, pi]);app.use(all);
Error Handling
Koa 提供了默认的错误处理机制,包括 try-catch和 Error 事件。自定义 try-catch捕获的推荐方式如下所示:
app.use(async (ctx, next) => { try { await next(); } catch (err) { err.status = err.statusCode || err.status || 500; throw err; }});
自定义监听 Error 事件:
app.on('error', (err, ctx) { // ...});
Koa Instance
Koa 的实例 app包含以下属性:
- app.name,可选,为应用程序指定名称
- app.env,默认值为 NODE_ENV 或 “development”
- app.proxy
- app.subdomainOffset
- app.context,Koa 推荐使用该命名空间挂载数据
app.context.db = db();
包含以下方法:
- app.listen(),设置监听端口
- app.callback()
- app.use(),注入中间件
- app.keys=,设置 Signed Cookie 的密钥
Context
每一个请求都有一个 Context对象,该对象又包含 request和 response两个对象:
app.use(async (ctx, next) => { // Context ctx; // Request ctx.request; // Response ctx.response; });
Context 对象包含的属性:
- ctx.req,Node.js 的 request 对象
- ctx.res,Node.js 的 response 对象
- ctx.request,koa 的 request 对象
- ctx.response,koa 的 response 对象
- ctx.state,建议将全局状态挂载在该命名空间下
- ctx.app,对应用实例的引用
Context 对象包含以下方法:
- ctx.cookies.get(name, [options]),获取 cookies
- ctx.cookies.set(name, value, [options]),设置 cookies
- ctx.throw([msg], [status], [properties]),抛出错误
ctx.throw('name required', 400);// 等同于const err = new Error('name required');err.status = 400;throw err;
Request
该对象是对 Node 原生 Request 对象的再封装,包含以下只读属性:
- request.href
- request.stale
- request.fresh,判断内容是否已经更新
- request.origin
- request.secure,检查是否是 HTTPS 协议
- request.charset
- request.originalUrl
- request.type,获取 Content-Type
- request.header,等同于 request.headers
- request.length,返回请求头信息中 Content-Length的值,如果不存在,则返回 undefined
- request.host,包含主机名和端口号,如果 app.proxy的值为 true,则支持 X-Forwarded-Host
- request.protocol,如果 app.proxy的值为 true,则支持 X-Forwarded-Host
- request.hostanme,如果 app.proxy的值为 true,则支持 X-Forwarded-Host
- request.ip,如果 app.proxy的值为 true,则支持 X-Forwarded-Host
- request.ips,仅当 app.proxy为 true 时返回 X-Forwarded-Host列表,否则返回空数组
- request.subdomains,根据 app.subdomainOffset返回子域名
包含以下可读写属性:
- request.url
- request.path
- request.method
- request.search
- request.querystring
- request.query
包含以下方法:
- request.is(type...),判断 Content-Type的类型,如果不存在 request.body,返回 undefined;如果没有符合的类型,返回 false;存在符合的类型则返回响应的字符串
- request.accepts(types)
- request.acceptsEncodings(types)
- request.acceptsCharsets(charsets)
- request.acceptsLanguages(langs)
// With Content-Type: text/html; charset=utf-8ctx.is('html'); // => 'html'ctx.is('text/html'); // => 'text/html'ctx.is('text/*', 'text/html'); // => 'text/html'// When Content-Type is application/jsonctx.is('json', 'urlencoded'); // => 'json'ctx.is('application/json'); // => 'application/json'ctx.is('html', 'application/*'); // => 'application/json'ctx.is('html'); // => false
Response
该对象是对 Node 原生 Response 对象的再封装,包含以下只读属性
- response.socket
- response.header,等同于 response.headers
- response.headerSent,检查响应头是否已发送
包含以下可读写属性:
- response.stauts
- response.message
- response.length
- response.body
- response.type
- response.lastModified
- response.etag
tx.response.etag = crypto.createHash('md5').update(ctx.body).digest('hex');
包含以下方法:
- response.get(field)
- response.set(fields)
- response.vary(field)
- response.set(field, value)
- response.append(field, value)
- response.remove(field)
- response.is(types...)
- response.flushHeaders()
- response.redirect(url, [alt])
- response.attachment([filename]),将 Content-Disposition设为 attachment,并通知客户端下载资源

HTML是一种用于构建网页的语言,通过标签和属性定义网页结构和内容。1)HTML通过标签组织文档结构,如、。2)浏览器解析HTML构建DOM并渲染网页。3)HTML5的新特性如、、增强了多媒体功能。4)常见错误包括标签未闭合和属性值未加引号。5)优化建议包括使用语义化标签和减少文件大小。

WebDevelovermentReliesonHtml,CSS和JavaScript:1)HTMLStructuresContent,2)CSSStyleSIT和3)JavaScriptAddSstractivity,形成thebasisofmodernWebemodernWebExexperiences。

HTML的作用是通过标签和属性定义网页的结构和内容。1.HTML通过到、等标签组织内容,使其易于阅读和理解。2.使用语义化标签如、等增强可访问性和SEO。3.优化HTML代码可以提高网页加载速度和用户体验。

htmlisaspecifictypefodyfocusedonstructuringwebcontent,而“代码” badlyLyCludEslanguagesLikeLikejavascriptandPytyPythonForFunctionality.1)htmldefineswebpagertuctureduseTags.2)“代码”代码“ code” code code code codeSpassSesseseseseseseseAwiderRangeLangeLangeforLageforLogageforLogicIctInterract

HTML、CSS和JavaScript是Web开发的三大支柱。1.HTML定义网页结构,使用标签如、等。2.CSS控制网页样式,使用选择器和属性如color、font-size等。3.JavaScript实现动态效果和交互,通过事件监听和DOM操作。

HTML定义网页结构,CSS负责样式和布局,JavaScript赋予动态交互。三者在网页开发中各司其职,共同构建丰富多彩的网站。

HTML适合初学者学习,因为它简单易学且能快速看到成果。1)HTML的学习曲线平缓,易于上手。2)只需掌握基本标签即可开始创建网页。3)灵活性高,可与CSS和JavaScript结合使用。4)丰富的学习资源和现代工具支持学习过程。

AnexampleOfAstartingTaginHtmlis,beginSaparagraph.startingTagSareEssentialInhtmlastheyInitiateEllements,defiteTheeTheErtypes,andarecrucialforsstructuringwebpages wepages webpages andConstructingthedom。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

Atom编辑器mac版下载
最流行的的开源编辑器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

Dreamweaver CS6
视觉化网页开发工具

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),