Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
/koaPublic
forked fromkoajs/koa

Expressive middleware for node.js using generators

License

NotificationsYou must be signed in to change notification settings

nswbmw/koa

 
 

Repository files navigation

Koa middleware framework for nodejs

gitterNPM versionbuild statusTest coverageOpenCollective BackersOpenCollective SponsorsPR's Welcome

Expressive HTTP middleware framework for node.js to make web applications and APIs more enjoyable to write. Koa's middleware stack flows in a stack-like manner, allowing you to perform actions downstream then filter and manipulate the response upstream.

Only methods that are common to nearly all HTTP servers are integrated directly into Koa's small ~570 SLOC codebase. Thisincludes things like content negotiation, normalization of node inconsistencies, redirection, and a few others.

Koa is not bundled with any middleware.

Installation

Koa requiresnode v7.6.0 or higher for ES2015 and async function support.

$ npm install koa

Hello Koa

constKoa=require('koa');constapp=newKoa();// responseapp.use(ctx=>{ctx.body='Hello Koa';});app.listen(3000);

Getting started

  • Kick-Off-Koa - An intro to Koa via a set of self-guided workshops.
  • Workshop - A workshop to learn the basics of Koa, Express' spiritual successor.
  • Introduction Screencast - An introduction to installing and getting started with Koa

Middleware

Koa is a middleware framework that can take two different kinds of functions as middleware:

  • async function
  • common function

Here is an example of logger middleware with each of the different functions:

async functions (node v7.6+)

app.use(async(ctx,next)=>{conststart=Date.now();awaitnext();constms=Date.now()-start;console.log(`${ctx.method}${ctx.url} -${ms}ms`);});

Common function

// Middleware normally takes two parameters (ctx, next), ctx is the context for one request,// next is a function that is invoked to execute the downstream middleware. It returns a Promise with a then function for running code after completion.app.use((ctx,next)=>{conststart=Date.now();returnnext().then(()=>{constms=Date.now()-start;console.log(`${ctx.method}${ctx.url} -${ms}ms`);});});

Koa v1.x Middleware Signature

The middleware signature changed between v1.x and v2.x. The older signature is deprecated.

Old signature middleware support will be removed in v3

Please see theMigration Guide for more information on upgrading from v1.x andusing v1.x middleware with v2.x.

Context, Request and Response

Each middleware receives a KoaContext object that encapsulates an incominghttp message and the corresponding response to that message.ctx is often usedas the parameter name for the context object.

app.use(async(ctx,next)=>{awaitnext();});

Koa provides aRequest object as therequest property of theContext.
Koa'sRequest object provides helpful methods for working withhttp requests which delegate to anIncomingMessagefrom the nodehttp module.

Here is an example of checking that a requesting client supports xml.

app.use(async(ctx,next)=>{ctx.assert(ctx.request.accepts('xml'),406);// equivalent to:// if (!ctx.request.accepts('xml')) ctx.throw(406);awaitnext();});

Koa provides aResponse object as theresponse property of theContext.
Koa'sResponse object provides helpful methods for working withhttp responses which delegate to aServerResponse.

Koa's pattern of delegating to Node's request and response objects rather than extending themprovides a cleaner interface and reduces conflicts between different middleware and with Nodeitself as well as providing better support for stream handling. TheIncomingMessage can still bedirectly accessed as thereq property on theContext andServerResponse can be directlyaccessed as theres property on theContext.

Here is an example using Koa'sResponse object to stream a file as the response body.

app.use(async(ctx,next)=>{awaitnext();ctx.response.type='xml';ctx.response.body=fs.createReadStream('really_large.xml');});

TheContext object also provides shortcuts for methods on itsrequest andresponse. In the priorexamples,ctx.type can be used instead ofctx.response.type andctx.accepts can be usedinstead ofctx.request.accepts.

For more information onRequest,Response andContext, see theRequest API Reference,Response API Reference andContext API Reference.

Koa Application

The object created when executingnew Koa() is known as the Koa application object.

The application object is Koa's interface with node's http server and handles the registrationof middleware, dispatching to the middleware from http, default error handling, as well asconfiguration of the context, request and response objects.

Learn more about the application object in theApplication API Reference.

Documentation

Troubleshooting

Check theTroubleshooting Guide orDebugging Koa inthe general Koa guide.

Running tests

$ npm test

Reporting vulnerabilities

To report a security vulnerability, please do not open an issue, as this notifies attackers of the vulnerability. Instead, please emaildead_horse,jonathanong, andniftylettuce to disclose.

Authors

SeeAUTHORS.

Community

Job Board

Looking for a career upgrade?

Backers

Support us with a monthly donation and help us continue our activities.

Sponsors

Become a sponsor and get your logo on our README on Github with a link to your site.

License

MIT

About

Expressive middleware for node.js using generators

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript100.0%

[8]ページ先頭

©2009-2025 Movatter.jp