Handler and Context

Handler - 클라이언트에 데이터를 다시 전송하는 리소스 또는 route 함수입니다.

ts
import { Elysia } from 'elysia'

new Elysia()
    // `() => 'hello world'` is a handler
    .get('/', () => 'hello world')
    .listen(3000)

handler는 리터럴 값일 수도 있습니다. Handler를 참조하세요.

ts
import { Elysia } from 'elysia'

new Elysia()
    // `() => 'hello world'` is a handler
    .get('/', 'hello world')
    .listen(3000)

인라인 값을 사용하는 것은 파일과 같은 정적 리소스에 유용할 수 있습니다.

Context

각 요청에 대한 정보를 포함합니다. handler의 유일한 인수로 전달됩니다.

typescript
import { 
Elysia
} from 'elysia'
new
Elysia
()
.
get
('/', (
context
) =>
context
.
path
)
// ^ This is a context

Context는 다음과 같은 요청에 대한 정보를 저장합니다:

  • body - 폼 데이터, JSON 페이로드와 같이 클라이언트가 서버로 보낸 데이터
  • query - query string을 객체로 표현 (Query는 '?' 물음표 기호부터 시작하는 pathname 뒤의 값에서 추출됩니다)
  • params - Path parameters를 객체로 파싱
  • headers - HTTP Header, "Content-Type"과 같은 요청에 대한 추가 정보

자세한 내용은 Context를 참조하세요.

Preview

에디터 섹션 아래에서 결과를 미리 볼 수 있습니다.

미리보기 창의 왼쪽 상단에 작은 네비게이터가 있어야 합니다.

이를 사용하여 경로와 메서드를 전환하여 응답을 확인할 수 있습니다.

또한 를 클릭하여 body와 headers를 편집할 수 있습니다.

과제

context 매개변수를 추출해 봅시다:

  1. Create POST endpoint

    Let's a POST endpoint "/", so we can send a body

  2. Extract Body

    Let's extract a body a return it as `return { body }`

  3. Extract Query

    Let's extract a query a return it as `return { body, query }`

  4. Extract Headers

    Let's extract a header a return it as `return { body, query, headers }`

Show answer
  1. 콜백 함수의 첫 번째 값에서 body, query, headers를 추출할 수 있습니다.
  2. 그런 다음 { body, query, headers }처럼 반환할 수 있습니다.
typescript
import { Elysia } from 'elysia'

new Elysia()
	.post('/', ({ body, query, headers }) => {
		return {
			query,
			body,
			headers
		}
	})
	.listen(3000)
  • index.ts

Error

Error: No Elysia server is running in index.ts
Did you forget to call `.listen()`?
    at parse (file:///vercel/path0/docs/.vitepress/.temp/utils.J44kKQwQ.js:202:66)
    at file:///vercel/path0/docs/.vitepress/.temp/utils.J44kKQwQ.js:240:30
    at new Promise (<anonymous>)
    at execute (file:///vercel/path0/docs/.vitepress/.temp/utils.J44kKQwQ.js:238:49)
    at Proxy.run (file:///vercel/path0/docs/.vitepress/.temp/store.CFqL75-f.js:190:51)
    at Proxy.wrappedAction (file:///vercel/path0/node_modules/pinia/dist/pinia.mjs:1394:26)
    at setup (file:///vercel/path0/docs/.vitepress/.temp/playground.eEZCBItr.js:133:50)
    at playground_vue_vue_type_script_setup_true_lang_default.setup (file:///vercel/path0/docs/.vitepress/.temp/playground.eEZCBItr.js:438:22)
    at callWithErrorHandling (/vercel/path0/node_modules/@vue/runtime-core/dist/runtime-core.cjs.prod.js:86:19)
    at setupStatefulComponent (/vercel/path0/node_modules/@vue/runtime-core/dist/runtime-core.cjs.prod.js:6365:25)