본문 바로가기

Manual/Node.js

Koa ctx (context) Manual

  • ctx : Context의 줄임말로 웹 요청과 응답에 관한 정보를 지닌 객체
app.use(async ctx => {
  ctx; // is the Context
  ctx.request; // is a Koa Request
  ctx.response; // is a Koa Response
});

Many of the context's accessors and methods simply delegate to their ctx.request or ctx.response equivalents for convenience, and are otherwise identical. For example ctx.type and ctx.length delegate to the response object, and ctx.path and ctx.method delegate to the request.

 

=>

대충 ctx.request 와 ctx.response 는 편의상 생략되고 하위 객체를 바로 불러오도록 사용할수있다는 뜻. (자주 사용해서)

실제로도 코딩할때 생략하는 경우가 매우 많다. 

 

예를 들어 ctx.type및 ctx.length 는 response 객체, ( ctx.response.type ctx.response.length )

ctx.path과 ctx.method 는 request 객체. ( ctx.request.path ctx.request.method )

 

Context API

Context 특정 메서드 및 접근자.

API Syntax Description
Node ctx.req
ctx.res
Node.js 상의 메소드로 접근
Request ctx.request koa Request 객체
Response ctx.response Koa Response 객체
State ctx.state Koa State 객체
App ctx.app Application 인스턴스 객체
Cookie ctx.cookies.get(name, [option])
ctx.cookies.set(name, value, [option])
쿠키 사용 ( 일반적으로 쿠키를 사용함 ) 메소드.
// value 에 들어가는값은 5.Cookie 항목 참고.
Throw ctx.throw([status], [msg], [properties]) Koa 의 에러 처리응답 ( .status ) 메소드
Assert ctx.assert(value, [status], [msg], [properties]) !value 에 대한 에러 처리응답 메소드
Respond ctx.respond Koa 내장 에러 처리응답 우회

주로 Request / Response ( 이두개는 당연한거지만 ), State, Cookie, Throw 와 가장 자주 인사하게 될것이다.

 

0. Node 접근 API ( 자주 사용되지는 않음 )

더보기

ctx.req

Node의 request 객체 (Node.js 상)

ctx.res

Node의 response 객체 (Node.js 상)

 

Bypassing Koa's response handling is not supported. Avoid using the following node properties:

=> Koa 내에서 request, response 를 수행할때 다음 메소드들을 Node 로 우회처리를 하지 말라는뜻

  • res.statusCode
  • res.writeHead()
  • res.write()
  • res.end()

 

1. Request Object

ctx.request

Koa Request 객체

Request API

A Koa Request object is an abstraction on top of node's vanilla request object, providing additional functionality that is useful for every day HTTP server development.

=> Koa Request 객체는 Node의 기본 요청 객체 위에 있는 추상화 객체이다.

HTTP 서버 개발에 유용한 추가 기능을 제공한다.

API Syntax Description
header ctx.request.header
ctx.request.header=
Request header 객체
Request header 객체 설정하기
headers ctx.request.headers
ctx.request.headers=
용도가 위와 같음.
method ctx.request.method
ctx.request.method=
Request method
Request method 설정.
methodOverride() 와 같은 유용한 미들웨어를 구현하는데 유용.
length ctx.request.length Request Content-Length 가 존재하는 경우 숫자로 반환하거나 그렇지 않을경우 undefined 처리.
url ctx.request.url
ctx.request.url=
 
originUrl ctx.request.originUrl  
origin ctx.request.origin  
href ctx.request.href  
path ctx.request.path
ctx.request.path=
 
querystring ctx.request.querystring
ctx.request.querystring=
 
search ctx.request.search
ctx.request.search=
 
host ctx.request.host  
hostname ctx.request.hostname  
URL ctx.request.url  
type ctx.request  
charset ctx.request.charset  
query ctx.request.query
ctx.request.query=
 
fresh ctx.request.fresh  
stale ctx.request.stale  
protocol ctx.request.protocol  
secure ctx.request.secure  
ip ctx.request.ip  
ips ctx.request.ips  
subdomains ctx.request.subdomains  
is ctx.request.is(types...)  
accepts ctx.request.accepts(types)  
acceptsEncodings ctx.request.acceptsEncodings(encodings)  
acceptsCharsets ctx.request.acceptsCharsets(charsets)  
acceptsLanguages ctx.request.acceptsLanguages(langs)  
idempotent ctx.request.idempotent  
socket ctx.request.socket  
get ctx.request.get(field)  

 

2. Response Object

ctx.response

Koa Response 객체

 

3. State Object

ctx.state

The recommended namespace for passing information through middleware and to your frontend views.

-> 네임스페이스 를 프론트 단 뷰로 전달하기에 권장되는 예시 

ctx.state.user = await User.find(id);

 

4. App Object

ctx.app

애플리케이션 인스턴스 참조(객체).

 

5. Cookie

ctx.cookies.get(name, [options])

Get cookienamewithoptions:

  • signedthe cookie requested should be signed

=> 서명된 쿠키를 Get 요청. 첫번째 인자는 name, 두번째 인자는 option

 

Koa uses thecookiesmodule where options are simply passed.

=> Koa 는 심플한 passed 에 쿠키 모듈 기반을 사용함.

ctx.cookies.set(name, value, [options])

Set cookienametovaluewithoptions:

=> 특정 쿠키를 2번째 파라미터 value 에 해당하는 쿠키로 설정해준다.

 

다음은 사용가능한 value 의 목록 (2번째 파라미터의 목록) 이다.

  • maxAge a number representing the milliseconds from Date.now() for expiry

=> Date.now() (Date.now() 메소드는 UTC 기준으로 1970년 1월 1일 0시 0분 0초부터 현재까지 경과된 밀리 초를 반환합니다.) 에서 불러오는 만료를 위한 Date.now 의 밀리초를 나타냄

( 쿠키의 최대 수명을 밀리초로 설정. )

  • signed sign the cookie value

=> 쿠키에 서명하기

  • expires a Date for cookie expiration

=> 지속적인 쿠키에 대한 만기 날짜를 설정

  • path cookie path, '/' by default

=> 쿠키 경로 설정. 기본값은 '/'

  • domain cookie domain

=> 쿠키의 도메인 경로 설정

  • secure secure cookie

=> 쿠키 보안 설정

  • httpOnly server-accessible cookie,trueby default

=> 쿠키의 서버 접근 가능 권한 설정. 기본값은 'true'

  • overwrite a boolean indicating whether to overwrite previously set cookies of the same name (falseby default). If this is true, all cookies set during the same request with the same name (regardless of path or domain) are filtered out of the Set-Cookie header when setting this cookie.

=> 쿠키 재사용 여부 체크. 기본값은 'false'

이것이 true 면 이 쿠키를 설정할 때 동일한 request에서 동일한 name 으로된 쿠키를 필터링해서 가져옴. (경로 또는 도메인에 관계없이, 모든 쿠키가 Set-Cookie 헤더에서 같은 쿠키로 설정되도록 )

 

6. Throw

ctx.throw([status], [msg], [properties])

Helper method to throw an error with a .status property defaulting to 500 that will allow Koa to respond appropriately. The following combinations are allowed:

 

=> .status property 와 error 를 뿌리는 Helper 메소드. Koa 가 적절하게 응답한다면 기본설정인 500을 응답.

ctx.throw(400);
ctx.throw(400, 'name required');
ctx.throw(400, 'name required', { user: user });

For example ctx.throw(400, 'name required') is equivalent to:

=> 아래 코드는 ctx.throw(400, 'name required') 과 같다.

한마디로 우리 throw 엄청 편하죠? 라는 느낌인데

const err = new Error('name required');
err.status = 400;
err.expose = true;
throw err;

Note that these are user-level errors and are flagged with err.expose meaning the messages are appropriate for client responses, which is typically not the case for error messages since you do not want to leak failure details.

You may optionally pass a properties object which is merged into the error as-is, useful for decorating machine-friendly errors which are reported to the requester upstream.

 

=> 이 코드는 user-level 에러를 의미하며, err.expose로 플래그가 지정되어 메시지가 클라이언트 응답에 적합함을 의미함. 일반적으로 오류 세부 정보를 누출하지 않기 때문에 오류 메시지의 경우는 아님.

가공하지 않은 기본 에러 처리를 컴퓨터가 알아먹기 좋도록 객체에 속성을 입혀 선택적 전달 할수 있음.

ctx.throw(401, 'access_denied', { user: user });

Koa uses http-errors to create errors.

=> Koa 는 JS http method - error 를 사용

7. Assert

ctx.assert(value, [status], [msg], [properties])

Helper method to throw an error similar to .throw() when !value. Similar to node's assert() method.

 

=> !value 가 발생할때 에러를 뿌리는 throw() 와 유사한 Helper 메소드. Node.js 의 assert() 메소드와 유사함.

ctx.assert(ctx.state.user, 401, 'User not found. Please login!');

Koa uses http-assert for assertions.

 

8. Respond ( 사용을 지양함 )

더보기

ctx.respond

To bypass Koa's built-in response handling, you may explicitly set ctx.respond = false;. Use this if you want to write to the raw res object instead of letting Koa handle the response for you.

 

=> Koa의 내장 응답 처리를 우회하려면 ctx.respond = false; 를 설정할 수 있다.

Koa가 응답을 처리하도록 하는 대신 기본 res 객체에 쓰려면 이것을 사용.

 

Note that using this is not supported by Koa. This may break intended functionality of Koa middleware and Koa itself. Using this property is considered a hack and is only a convenience to those wishing to use traditional fn(req, res) functions and middleware within Koa.

 

=> 이것을 사용하는 것은 Koa에서 지원하지 않는다. Koa 내에서 기존의 fn(req, res) 기능과 미들웨어를 사용하려는 사람들에게만 편리함. ( Koa 미들웨어 및 Koa 자체의 의도된 기능을 손상시킬 수 있고 해킹으로 간주된다고 하네요 )

옛날부터 쓰던방식이 편한 사람 아니면 건들지좀 마라 그냥 기존개발자 서비스용으로 만들어 둔거니깐,,

 

잘못된 내용이나 수정할 부분이 있으시면 댓글 부탁드립니다 !

내용이 길어서 아래 표를 확인하고 세부사항을 Ctrl + F 하시기 바랍니다.

+ 정확한 이해를 돕기위한 원문은 서비스 ( ,,,? )