目錄
Middleware
Error Handling
Koa Instance
Context
Request
Response
首頁 web前端 html教學 Koa2_html/css_WEB-ITnose

Koa2_html/css_WEB-ITnose

Jun 21, 2016 am 08:49 AM
koa2

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,并通知客户端下载资源
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

HTML容易為初學者學習嗎? HTML容易為初學者學習嗎? Apr 07, 2025 am 12:11 AM

HTML適合初學者學習,因為它簡單易學且能快速看到成果。 1)HTML的學習曲線平緩,易於上手。 2)只需掌握基本標籤即可開始創建網頁。 3)靈活性高,可與CSS和JavaScript結合使用。 4)豐富的學習資源和現代工具支持學習過程。

HTML,CSS和JavaScript的角色:核心職責 HTML,CSS和JavaScript的角色:核心職責 Apr 08, 2025 pm 07:05 PM

HTML定義網頁結構,CSS負責樣式和佈局,JavaScript賦予動態交互。三者在網頁開發中各司其職,共同構建豐富多彩的網站。

了解HTML,CSS和JavaScript:初學者指南 了解HTML,CSS和JavaScript:初學者指南 Apr 12, 2025 am 12:02 AM

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

HTML中起始標籤的示例是什麼? HTML中起始標籤的示例是什麼? Apr 06, 2025 am 12:04 AM

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

Gitee Pages靜態網站部署失敗:單個文件404錯誤如何排查和解決? Gitee Pages靜態網站部署失敗:單個文件404錯誤如何排查和解決? Apr 04, 2025 pm 11:54 PM

GiteePages靜態網站部署失敗:404錯誤排查與解決在使用Gitee...

如何用CSS3和JavaScript實現圖片點擊後周圍圖片散開並放大效果? 如何用CSS3和JavaScript實現圖片點擊後周圍圖片散開並放大效果? Apr 05, 2025 am 06:15 AM

實現圖片點擊後周圍圖片散開並放大效果許多網頁設計中,需要實現一種交互效果:點擊某張圖片,使其周圍的...

HTML,CSS和JavaScript:Web開發人員的基本工具 HTML,CSS和JavaScript:Web開發人員的基本工具 Apr 09, 2025 am 12:12 AM

HTML、CSS和JavaScript是Web開發的三大支柱。 1.HTML定義網頁結構,使用標籤如、等。 2.CSS控製網頁樣式,使用選擇器和屬性如color、font-size等。 3.JavaScript實現動態效果和交互,通過事件監聽和DOM操作。

網頁批註如何實現Y軸位置的自適應佈局? 網頁批註如何實現Y軸位置的自適應佈局? Apr 04, 2025 pm 11:30 PM

網頁批註功能的Y軸位置自適應算法本文將探討如何實現類似Word文檔的批註功能,特別是如何處理批註之間的間�...

See all articles