Docs
Routing
Context
Context
Starting from v2, the parameter context
is provided instead of req
and res
in handlers.
Typescript
export default [(ctx) => {}];
#context.
Property/Method | Description | Same |
---|---|---|
context.status | Set HTTP status code | res.status |
context.headers | Set HTTP headers | res.headers |
context.body | Request Body (Provided with midddleware) | - |
context.params | Route parameters | res.params |
context.query | Query string parameters | res.query |
Methods | ||
context.send() | Send a response | res.end() |
context.header() | Set a specific header | res.setHeader() |
context.html() | Send an HTML response | - |
context.json() | Send a JSON response | res.json() |
context.text() | Send a plain text response | res.text() |
#Request and response
Typescript
export default [
(ctx) => {
const req = ctx.request; // request
const res = ctx.response; // response
},
];
#Reference
Typescript
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { ParsedUrlQuery } from 'node:querystring';
import { URL } from 'node:url';
import type { Nullable, JsonType } from '../types';
import { SentaResponse } from './response';
export interface DevelopmentEnvironment {
pattern: RegExp;
path: string;
params: string[];
}
export declare class Context {
/**
* `node:http.IncomingMessage`
*
* default nodejs request type
*
* @alias `ctx.res`
*/
request: IncomingMessage;
/**
* `node:http.ServerResponse`
*
* default nodejs response type
*
* @alias `ctx.res`
*/
response: ServerResponse;
/**
* query data
*
* ```txt
* /abc?foo=bar => {foo: "bar"}
* ```
*/
query: ParsedUrlQuery;
/**
* ```txt
* /api/users.ts => GET /api/users => {}
* /api/user/[id]/index.ts => GET /api/user/hello => {id: "hello"}
* ```
*/
params: Record<string, string | null>;
url: URL;
pathname: string;
__DEV__: Nullable<DevelopmentEnvironment>;
constructor(
req: IncomingMessage,
res: ServerResponse,
init?: {
path: string;
params: string[];
},
);
send(
chunk: string | number | JsonType | boolean | bigint | SentaResponse,
status?: number,
): void;
html(body: string): void;
json(body: JsonType): void;
text(body: string): void;
redirect(url: string, status?: number): void;
/**
* set only one header
*
* ```ts
* ctx.setHeader('Content-Type', 'text/plain');
* ```
*
* @param field header field
* @param value header value
* @returns context
*/
set(field: string, value: string): this;
/**
* set multiple headers
*
* ```ts
* ctx.headers({"foo": "bar"});
* ```
* @param headers Headers object
*/
headers(headers: JsonType): void;
status(status: number): this;
}