k.request
HTTP request information - obtain client request data, query parameters, form fields, files, and metadata
| Execution Context | Prerequisites | Typical Use |
|---|---|---|
| KScript APIs, Page / Layout / View server scripts | None | Read query/form/JSON inputs, handle file uploads, and switch request culture |
k.request provides access to incoming HTTP request data including query parameters, form fields, uploaded files, parsed request models, headers, client metadata, and culture controls.
Quick Start
k.api.post(() => {
// Parse k.request.body explicitly when query params (e.g. ?page=1) may coexist with a JSON body
let payload = null
if (k.request.form.length > 0) {
payload = k.request.form
} else if (k.request.body) {
try {
payload = JSON.parse(k.request.body)
} catch (e) {
payload = k.request.body
}
}
return {
method: k.request.method,
page: k.request.queryString.get("page"),
payload,
ip: k.request.clientIp
}
})Quick Reference
| Method / Property | Description | Returns |
|---|---|---|
queryString | URL query parameters dictionary | KDictionary |
form | POST/PUT form fields dictionary | KDictionary |
files | Uploaded file collection (with save(filename)) | UploadFile[] |
body | Raw request body text (parse JSON manually) | string |
model | Parsed JSON body or form/queryString dictionary (null when empty; query/form parameters overwrite JSON body) | any |
headers | HTTP request headers dictionary (stored keys strip -) | KDictionary |
method | HTTP method name (GET, POST, etc.) | string |
clientIp | Client IP address string | string |
clientCountry | IP geolocation metadata | CountryLocationModel |
url | Request path and query string | string |
host | Request hostname | string |
culture | Active request culture code | string |
page | Current rendered Page object (null in standalone APIs) | Page | null |
get(key) | Read value from query, form, headers, cookies, device, JSON body, or route parameter | string | null |
setCulture(culture) | Temporarily override active request culture | void |
resetCulture() | Restore initial request culture | void |
Properties
queryString
Get URL query parameters.
// GET /api/users?page=1&limit=10
k.api.get(() => {
const page = k.request.queryString.get("page") // "1"
const limit = k.request.queryString.get("limit") // "10"
return { page, limit }
})
// Returns: { "page": "1", "limit": "10" }form
Get form data for POST/PUT requests.
k.api.post(() => {
const data = k.request.form
return { received: data }
})files
Get uploaded files.
k.api.post(() => {
if (k.request.files.length > 0) {
k.request.files.forEach((item) => {
// Save to site files
item.save(item.fileName)
})
}
return { uploaded: k.request.files.length }
})headers
Get HTTP request headers.
k.api.get(() => {
const headers = k.request.headers
return {
accept: headers.get("Accept"),
userAgent: headers.get("User-Agent"), // get() strips "-" automatically
hasUserAgent: headers.containsKey("UserAgent"), // containsKey / [] / keys require no "-"
cookie: headers.get("Cookie")
}
})Header keys are stored without hyphens (-)
k.request.headers strips hyphens (-) when populating stored keys (storing "UserAgent" instead of "User-Agent"). While headers.get("User-Agent") strips hyphens during lookup and succeeds, headers.containsKey(...), bracket indexing (headers[...]), and headers.keys do not—use hyphen-free names such as "UserAgent" or "ContentType" for those.
clientIp
Get the client IP address string.
k.api.get(() => {
return { ip: k.request.clientIp }
})
// Returns: { "ip": "120.36.245.209" }body
Get the raw request body text (typically for POST/PUT).
Note
k.request.body returns a raw string and must be parsed manually for JSON payloads:
const data = JSON.parse(k.request.body || "{}")k.api.post(() => {
const body = k.request.body
return { body }
})Parse JSON data:
k.api.post(() => {
const { username } = JSON.parse(k.request.body || '{}')
return { username }
})method
Get the HTTP request method.
k.api.get(() => {
return { method: k.request.method }
})
// Returns: { "method": "GET" }url / host
Get the URL and hostname of the current request.
k.api.get(() => {
return {
url: k.request.url, // "/api/users"
host: k.request.host // "example.kooboo.cn"
}
})culture / setCulture() / resetCulture()
Read or temporarily switch the culture (language) of the current request, affecting language-sensitive APIs such as k.t() and k.content.
const culture = k.request.culture // e.g. "en-US"
k.request.setCulture("zh-CN")
const text = k.t("welcome") // resolves zh-CN text
k.request.resetCulture() // restores initial request culturemodel
Aggregated request payload object or null: it first parses a valid JSON request body, and then—whenever any form or queryString parameter is present—builds a merged form + queryString dictionary that unconditionally overwrites the parsed JSON body. If the body is not JSON and both form and queryString are empty, it returns null (not {}).
// GET /api/demo?a=1&b=two -> { "a": "1", "b": "two" }
// POST {"x":10} (no query/form) -> { "x": 10 }
// Empty request -> null
k.api.get(() => {
return { model: k.request.model }
})Two caveats with model
- Returns
nullwhen empty: Guard againstnull(such ask.request.model?.x) before reading properties, or aTypeErrorwill be thrown. queryString/formoverwrites JSON bodies: On a request such asPOST /api/demo?page=1with JSON body{"x":10},k.request.modelreturns{"page":"1"}and silently discards the JSON body. Parsek.request.bodyexplicitly withJSON.parse()whenever query parameters and a JSON body may coexist.
clientCountry
Client country/region information. Access countryCode, continent, latitude, and longtitude (exact spelling from source) in script code; when serialized directly to JSON, the keys use PascalCase (CountryCode, Continent, Latitude, Longtitude). When geolocation cannot resolve an IP, fields fall back to "ZZ", null, and 0.
const country = k.request.clientCountry
return { code: country?.countryCode }page
The Page resource currently being rendered (same type as in k.site.pages); returns null in non-page contexts such as standalone k.api calls.
const current = k.request.page
return { id: current?.id, url: current?.url }Methods
get(key)
Read a string value across request sources in the following lookup order:
queryString(URL query parameters, URL-decoded)form(form fields)headers(HTTP request headers)cookies(request cookies)- Built-in
"device"key (returns"Mobile"or"Desktop") - JSON request body properties (non-
GET, non-application/octet-streamrequests) - Dynamic route parameters /
DataContext
| Parameter | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Parameter key name |
Returns: string | null, or null if not found or reserved by a Request property name.
// Assume the API URL is /api/users/{id} and the request is /api/users/123
k.api.get(() => {
const id = k.request.get("id") // "123"
return { id }
})Lookup priority and reserved property names
- Priority order:
queryString→form→headers→cookies→"device"→ JSON body → dynamic route parameters. For example, if a query parameter shares a name with a route parameter,queryStringwins. - Keys matching
k.requestproperties always returnnull: Case-insensitively (exceptcultureandmodel), passing any key that matches a publicRequestproperty name—such aspage,url,host,method,body,form,files,headers,queryString,clientIp, orclientCountry—causesk.request.get(key)to unconditionally returnnull. For example, on?page=2,k.request.get("page")returnsnull; usek.request.queryString.get("page")instead.
TypeScript Definitions
Show full TypeScript definitions
interface Request {
queryString: KDictionary;
form: KDictionary;
files: UploadFile[];
body: string;
culture: string;
model: any;
method: string;
clientIp: string;
clientCountry: CountryLocationModel;
headers: KDictionary;
url: string;
host: string;
page: Page;
get(key: string): string;
setCulture(culture: string): void;
resetCulture(): void;
}
interface KDictionary extends Record<string, string> {
keys: string[];
values: string[];
length: number;
get(key: string): string;
add(key: string, value: string): void;
set(key: string, value: string): void;
clear(): void;
containsKey(key: string): boolean;
remove(key: string): boolean;
}
interface UploadFile {
bytes: number[];
contentType: string;
fileName: string;
name: string;
save(filename: string): FileInfo;
}
interface CountryLocationModel {
countryCode: string;
continent: string;
latitude: number;
longtitude: number;
}Related Docs
- k.response — HTTP response handling
- k.cookie — Cookie management
- k.session — Session state