17koa/koa-guide

Name: koa-guide

Owner: 17koa

Description: koa guide in Chinese

Created: 2016-05-04 11:22:38.0

Updated: 2017-10-30 07:20:32.0

Pushed: 2015-11-16 12:47:02.0

Homepage:

Size: 268

Language: null

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

koa ???? koa@npm Build Status

NPM NPM

Koa???? Node.js web ??

koa ??

? Express ??????? koa?????????????????????? Web ????? koa ?? web ?????????? generator????????????????????????????????Koa ???????????????????????????????????? Web ?????????

?? koa

koa ???? generator ? Node ????????? node >= 0.11.9 ???????????????? Node ????????? n ??????????????? 0.11.x:

m install -g n
0.11
de --harmony my-koa-app.js

??????????? $ node --harmony app.js ??harmony ???????

???????? node ??????? harmony ??????

s node='node --harmony'

???Application?

?? Koa Application????? app????? generator ????????????????????????????Koa app ??????????? Ruby Rack ?? Connect/Express ??????????????????????Koa ????????????????????????????????????????

????????????????content-negotation???????cache freshness???????proxy support?????????????????? ??? ?????????? Koa ???????????????????? Koa ????? Hello World ?????

koa = require('koa');
app = koa();

use(function *(){
is.body = 'Hello World';


listen(3000);

????Koa 2???

Koa = require('koa');
app = new Koa();

use(ctx => {
x.body = 'Hello World';


listen(3000);

???? ???? function ???generator functions ? function* ???????????????? yield?generator function?ECMAScript 6???????????????????Koa????generator function?????js?????????????????????????????


?????Cascading?

Koa ???????????????????????????????

???? Node ????????????????????????? Koa ????????????????????? Connect ????????????Koa ?????????????????????????????????Koa ?????????????????????????? yield next ?????????????????????downstream??? yield next ???????????????????????upstream??

???????????????????? Hello World ?????????????? x-response-time ???? logging ?????????????????????????? response ??????????????? ?Hello World??

?????? yield next ??????????????????????????????????????????????????????? downstream???????????? downstream ?????????????

koa = require('koa');
app = koa();

-response-time
use(function *(next){
 (1) ????
r start = new Date;
eld next;
 (5) ???? x-response-time ??????2??????????????
r ms = new Date - start;
is.set('X-Response-Time', ms + 'ms');
 (6) ?? this.body


ogger
use(function *(next){
 (2) ?? logger ???
r start = new Date;
eld next;
 (4) ???? logger ??????2??????????????
r ms = new Date - start;
nsole.log('%s %s - %s', this.method, this.url, ms);


esponse
use(function *(){
 (3) ?? response ???????????????????????? upstream
is.body = 'Hello World';


listen(3000);

??????????????????????????????????????????????????????????????????

???? ????????????? CSS ???????????????????????????????????? LESS ??????????

dleware1 {
 (1) do some stuff
iddleware2 {
// (2) do some other stuff
.middleware3 {
  // (3) NO next yield !
  // this.body = 'hello world'
}
// (4) do some other stuff later

 (5) do some stuff lastest and return

???????????????????????????? ruby ??????block?? yield ????????????????? koa ??????

???? ?????????? Django Middleware

onion.png


?????Settings?

?????? app ???????????Koa ???????


????Middleware?

????
app.listen(…)

????????????????????? 3000 ???????????

koa = require('koa');
app = koa();

listen(3000);

app.listen ? http.createServer ???????????????

http = require('http');
koa = require('koa');
app = koa();

.createServer(app.callback()).listen(3000);

??????????????????? app??????? HTTP ? HTTPS?

http = require('http');
koa = require('koa');
app = koa();

.createServer(app.callback()).listen(3000);
.createServer(app.callback()).listen(3001);
app.callback()

?????? http.createServer() ??????????????????????? Connect/Express ????

app.use(function)

???? function ?????????????? ??? ??

app.keys=

?????? Cookie ????????????? KeyGrip ???????????????????

keys = ['im a newer secret', 'i like turtle'];
keys = new KeyGrip(['im a newer secret', 'i like turtle'], 'sha256');

???????????? signed ??????????

.cookies.set('name', 'tobi', { signed: true });
?????Error Handling?

?? NODE_ENV ???? "test"?Koa ????????????? stderr???????????????? Koa app ????????????????

on('error', function(err){
g.error('server error', err);

??? req ?? res ?????????????????Koa ??????????????????

on('error', function(err, ctx){
g.error('server error', err, ctx);

????????????????????????? socket ??Koa ??????? 500 ???????? app ???????????????


??????Context?

Koa ??????? request ? response ??????????????????????????????????????? ctx.request ? ctx.response ?????????

??????????????????????????????????? this ????

use(function *(){
is; // ?????
is.request; // Request ??
is.response; // Response ??

??????????????????????????? ctx.request ? ctx.response????? ctx.type ? ctx.length ????? response ???ctx.path ? ctx.method ????? request ???

Request ??

ctx.request ???????????????? Request ??

Response ??

ctx.response ???????????????? Response ??

????????? API

??????????

.throw(403)
.throw('name required', 400)
.throw(400, 'name required')
.throw('something exploded')

????this.throw('name required', 400) ????????????

err = new Error('name required');
status = 400;
w err;

???????ctx.throw ??????????????????err.expose???????????


Request

ctx.request ???? Node ?????????????????????????

??? Request ?? API ???

req.header

?????

req.method

??????

req.method=

?? req.method ??????? methodOverride() ????

req.length

?? req ??? Content-Length (Number)

req.url

???? url

req.url=

???? url????? url ??

req.path

???? pathname

req.path=

???? pathname????? url ????????????????

req.querystring

?? url ?????????????? '?'

req.querystring=

??????????? '?'

req.search

?? url ?????????????? '?'

req.search=

?????????? '?'

req.host

??????????????? app.proxy ??? true ???? X-Forwarded-Host?

req.type

?? req ??? Content-Type???? charset ????????

ct = this.type;
> "image/png"
req.query

??????????????? Express ?? req.query??????????????????

? url ??????? "color=blue&size=small" ???????


lor: 'blue',
ze: 'small'

req.query=

????????????????????

.query = { next: '/login' };
req.fresh

??????????????????????????????????? 304????????

.set('ETag', '123');

?????????
this.fresh) {
is.status = 304;
turn;


?????????????????
.body = yield db.find('something');
req.stale

? req.fresh ?????????

req.protocol

????????? "https" ?? "http"?? app.proxy ??? true ???? X-Forwarded-Proto?

req.secure

????????? HTTPS ????????? this.protocol == "https"

req.ip

????IP?? app.proxy ??? true ???? X-Forwarded-For?

req.ips

????IP????? app.proxy ??? true ???? X-Forwarded-For ????????????

req.subdomains

???????????????????????????????? . ????????????? app.subdomainOffset ??????????????????????

????????? "tobi.ferrets.example.com" ????? ["ferrets", "tobi"]????????????????????

????????????? app.subdomainOffset ? 3??????????? ["tobi"]?

req.is(type)

??????? Content-Type ????? type ??????????? request.body???? undefined????????????? false?????????????????

?? Content-Type: text/html; charset=utf-8
.is('html'); // => 'html'
.is('text/html'); // => 'text/html'
.is('text/*', 'text/html'); // => 'text/html'

?? Content-Type ? application/json ??
.is('json', 'urlencoded'); // => 'json'
.is('application/json'); // => 'application/json'
.is('html', 'application/*'); // => 'application/json'

.is('html'); // => false

?????????? req.is(type)?????????????????

this.is('image/*')) {
 process
se {
is.throw(415, 'images only!');

req.accepts(type)

??????? Accept ????? type ?????????????????????????????? false??????????? 406 “Not Acceptable” ?????????????????

ccept: text/html
.accepts('html');
> "html"

ccept: text/*, application/json
.accepts('html');
> "html"
.accepts('text/html');
> "text/html"
.accepts('json', 'text');
> "json"
.accepts('application/json');
> "application/json"

ccept: text/*, application/json
.accepts('image/png');
.accepts('png');
> undefined

ccept: text/*;q=.5, application/json
.accepts(['html', 'json']);
.accepts('html', 'json');
> "json"

??????????? Accept ?????????? type ??????

req.acceptsEncodings(encodings)

?????????????????????????????????????????????

ccept-Encoding: gzip
.acceptsEncodings('gzip', 'deflate');
> "gzip"

.acceptsEncodings(['gzip', 'deflate']);
> "gzip"

????????????????????

ccept-Encoding: gzip, deflate
.acceptsEncodings();
> ["gzip", "deflate"]
req.acceptsCharsets(charsets)

????? req.acceptsEncodings(encodings)

req.acceptsLanguages(langs)

????? req.acceptsEncodings(encodings)


Response

??? Response ?? API ???

res.header

?????

res.status

??????

res.status=

??????????????

res.length=

?????? Content-Length ??

res.length

?????? Content-Length ??????? Content-Length ?????? res.body ??

res.body

?? res.body?? res.body ? null ???????? 200 ??koa ???? 404 ???

res.body=

??????????????????????

res.get(field)

?????????????????????

etag = this.get('ETag');
res.set(field, value)

?????????????????

.set('Cache-Control', 'no-cache');
res.set(fields)

???????????????????

.set({
tag': '1234',
ast-Modified': date

res.remove(fields)

??????????

res.type

??????? Content-Type???? "charset" ????

ct = this.type;
> "image/png"
res.type=

???????????????? Content-Type

.type = 'text/plain; charset=utf-8';
.type = 'image/png';
.type = '.png';
.type = 'png';

??????????????koa ????????????????????? res.type = 'html' ??koa ????? "utf-8" ?????????? res.type = 'text/html' ????koa ??????????

res.redirect(url, [alt])

???? 302 ?????? url?????????? back ????? url ???????refer?????????????????? '/'

.redirect('back');
.redirect('back', '/index.html');
.redirect('/login');
.redirect('http://google.com');

??????? 302 ??????????????????????

.status = 301;
.redirect('/cart');
.body = 'Redirecting to shopping cart';
res.attachment([filename])

?????? Content-Disposition ? "attachment"????????????

res.headerSent

?????????????????????????????????????

res.lastModified

???????? Last-Modified ????????

res.lastModified=

??????? Last-Modified ???????????????????

.response.lastModified = new Date();
res.etag=

?????? Etag ???koa ????? Etag ??????

.response.etag = crypto.createHash('md5').update(this.body).digest('hex');

???Benchmarks?

???????????wrk ?? benchmarks ???

ddleware
.03

ddleware
.10

iddleware
.55

iddleware
.92

iddleware
.33

iddleware
.17

iddleware
.98

middleware
.37

?????????????50??????????????????? 340,260 ??/???? 20,415,600 ??/??????? 4.4 ? ??/??


????

???????? koa ?????????????????????


Contributing
MIT license

Copyright (c) 2013 turing <o.u.turing@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


docor

Generated using docor @ 0.1.0. brought to you by Guo Yu


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.