Skip to content

k.request ​

HTTP request information - obtain client request data, query parameters, form fields, files, and metadata

Execution ContextPrerequisitesTypical Use
KScript APIs, Page / Layout / View server scriptsNoneRead 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 ​

js
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 / PropertyDescriptionReturns
queryStringURL query parameters dictionaryKDictionary
formPOST/PUT form fields dictionaryKDictionary
filesUploaded file collection (with save(filename))UploadFile[]
bodyRaw request body text (parse JSON manually)string
modelParsed JSON body or form/queryString dictionary (null when empty; query/form parameters overwrite JSON body)any
headersHTTP request headers dictionary (stored keys strip -)KDictionary
methodHTTP method name (GET, POST, etc.)string
clientIpClient IP address stringstring
clientCountryIP geolocation metadataCountryLocationModel
urlRequest path and query stringstring
hostRequest hostnamestring
cultureActive request culture codestring
pageCurrent rendered Page object (null in standalone APIs)Page | null
get(key)Read value from query, form, headers, cookies, device, JSON body, or route parameterstring | null
setCulture(culture)Temporarily override active request culturevoid
resetCulture()Restore initial request culturevoid

Properties ​

queryString ​

Get URL query parameters.

js
// 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.

js
k.api.post(() => {
  const data = k.request.form
  return { received: data }
})

files ​

Get uploaded files.

js
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.

js
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.

js
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:

js
const data = JSON.parse(k.request.body || "{}")
js
k.api.post(() => {
  const body = k.request.body
  return { body }
})

Parse JSON data:

js
k.api.post(() => {
  const { username } = JSON.parse(k.request.body || '{}')
  return { username }
})

method ​

Get the HTTP request method.

js
k.api.get(() => {
  return { method: k.request.method }
})
// Returns: { "method": "GET" }

url / host ​

Get the URL and hostname of the current request.

js
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.

js
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 culture

model ​

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 {}).

js
// 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

  1. Returns null when empty: Guard against null (such as k.request.model?.x) before reading properties, or a TypeError will be thrown.
  2. queryString / form overwrites JSON bodies: On a request such as POST /api/demo?page=1 with JSON body {"x":10}, k.request.model returns {"page":"1"} and silently discards the JSON body. Parse k.request.body explicitly with JSON.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.

js
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.

js
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:

  1. queryString (URL query parameters, URL-decoded)
  2. form (form fields)
  3. headers (HTTP request headers)
  4. cookies (request cookies)
  5. Built-in "device" key (returns "Mobile" or "Desktop")
  6. JSON request body properties (non-GET, non-application/octet-stream requests)
  7. Dynamic route parameters / DataContext
ParameterTypeRequiredDescription
keystringYesParameter key name

Returns: string | null, or null if not found or reserved by a Request property name.

js
// 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

  1. 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, queryString wins.
  2. Keys matching k.request properties always return null: Case-insensitively (except culture and model), passing any key that matches a public Request property name—such as page, url, host, method, body, form, files, headers, queryString, clientIp, or clientCountry—causes k.request.get(key) to unconditionally return null. For example, on ?page=2, k.request.get("page") returns null; use k.request.queryString.get("page") instead.

TypeScript Definitions ​

Show full TypeScript definitions
ts
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;
}