k.response
HTTP response processing - write output, headers, views, binary/files, status codes, page meta, and redirects
| Execution Context | Prerequisites | Typical Use |
|---|---|---|
KScript APIs; meta/executeView/stop mainly in Page/Layout/View <script env="server"> | Referenced View or site file must exist for view/file helpers | Emit JSON/HTML/file downloads, set status codes & headers, redirect, and set head meta |
k.response provides methods for shaping HTTP responses, including writing bodies, setting headers, executing views, returning files or binary downloads, configuring status codes, stopping template rendering, redirecting, and setting page head metadata.
Quick Start
k.api.get(() => {
k.response.setHeader("Content-Type", "application/json; charset=utf-8")
k.response.setHeader("X-Served-By", "Kooboo")
k.response.json({ success: true, timestamp: Date.now() })
})Quick Reference
| Method / Property | Description | Returns |
|---|---|---|
meta | Read/write current page <title> and <meta> (matches k.page) | PageMeta |
write(value) | Write primitive or JSON-serialized object to body | void |
json(value) | Serialize JSON to body (keeps default Content-Type unless set) | void |
setHeader(key, value) | Set a custom HTTP response header | void |
statusCode(code) | Set the HTTP response status code | void |
unauthorized() | Set status code 401 (empty response body) | void |
notFound() | Set status code 404 | void |
redirect(url, absolute?) | Send an HTTP redirect response | void |
executeView(viewNameOrId) | Execute a View directly into the current response | void |
renderViewAsString(viewNameOrId) | Render a View and return its HTML string (null if missing) | string | null |
file(path, contentType?, fileName?) | Send a file from the k.file disk folder (always sets Content-Disposition: attachment) | void |
binary(contentType, bytes, filename?) | Send a binary byte-array response or download | void |
execute(url) | Render another site Page or fetch an http(s):// URL and append output | void |
stop() | Cancel downstream page/template rendering (use JS return to exit early) | void |
meta
k.response.meta is the object-style counterpart of k.page for configuring <title> and <meta> tags during HTML page/layout/view rendering (for example inside <script env="server">). Standalone JSON API endpoints do not render an HTML <head>.
| Member | Description |
|---|---|
meta.title | Read or write the page title |
meta.setMeta(name, content) | Set <meta name="..." content="..."> (name must be a non-null string) |
meta.setMeta(name, httpEquiv, charSet, content) | Set a meta tag with http-equiv / charset (name must be a non-null string) |
meta.getMeta(name) | Read an existing meta entry (MetaItem when present, null when missing) |
meta.setCustomerHeader(headerString) | Append a custom head HTML fragment |
<!-- Inside a Page or Layout server script -->
<script env="server">
k.response.meta.title = "Order detail"
k.response.meta.setMeta("description", "Order detail page")
k.response.meta.setMeta("charset", "Content-Type", "utf-8", "text/html")
k.response.meta.setCustomerHeader('<meta property="og:title" content="Order detail">')
const descMeta = k.response.meta.getMeta("description")
const descContent = descMeta ? descMeta.content : ""
</script>Reading MetaItem fields
MetaItem stores name, content, httpEquiv, charSet, and property as public fields on the runtime object. Read those properties directly in script rather than calling JSON.stringify(k.response.meta.getMeta(...)), which serializes as {}.
Methods
write()
Write content to the response body. Primitive values are emitted directly, while objects are serialized to JSON.
| Parameter | Type | Required | Description |
|---|---|---|---|
value | any | Yes | Content to write to the response body |
Returns: void.
k.api.get(() => {
k.response.write("hello world")
k.response.write(1234)
const obj = { name: "kooboo" }
k.response.write(obj)
})
// Output: hello world1234{"name":"kooboo"}json()
Serialize a value to JSON and write it to the response body. This method does not automatically change the Content-Type header (text/html; charset=UTF-8 by default); call k.response.setHeader("Content-Type", "application/json; charset=utf-8") when clients expect application/json.
| Parameter | Type | Required | Description |
|---|---|---|---|
value | any | Yes | Value to serialize as JSON |
Returns: void.
k.api.get(() => {
k.response.setHeader("Content-Type", "application/json; charset=utf-8")
k.response.json({
success: true,
data: { id: 1, name: "test" }
})
})
// Output: {"success":true,"data":{"id":1,"name":"test"}}executeView()
Render a View resource by name or ID and write its HTML directly into the current response output. Commonly used in Layouts, Pages, or server scripts to emit a View dynamically.
| Parameter | Type | Required | Description |
|---|---|---|---|
ViewNameOrId | string | Yes | View resource name or GUID |
Returns: void.
<!-- Inside a Page or Layout server script -->
<script env="server">
k.response.executeView("test")
</script>renderViewAsString()
Render a View resource by name or ID and return its rendered HTML as a string without immediately writing to the response.
| Parameter | Type | Required | Description |
|---|---|---|---|
ViewNameOrId | string | Yes | View resource name or GUID |
Returns: string | null, rendered HTML output, or null if the view does not exist.
k.api.get("preview", () => {
const html = k.response.renderViewAsString("test")
if (html === null) {
k.response.statusCode(404)
return { error: "View not found" }
}
return { html }
})file()
Stream a file from the site's k.file (FileIO) disk folder as a download response.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | Relative file path inside the k.file disk folder (not k.site.files) |
contentType | string | No | Response Content-Type; inferred from the file extension when omitted |
fileName | string | No | Download filename; Content-Disposition: attachment;filename=... is always added and defaults to the basename of path |
Returns: void. Throws "File not found" if the file does not exist; check k.file.exists(path) beforehand.
// Example API URL: /api/files/{action}
// Basic usage (infers MIME type and uses logo.png in Content-Disposition: attachment)
k.api.get("logo", () => {
const path = "images/logo.png"
if (!k.file.exists(path)) {
k.response.statusCode(404)
return { error: "File not found" }
}
k.response.file(path)
})
// Specify Content-Type and custom download filename
k.api.get("report", () => {
const path = "docs/report.pdf"
if (!k.file.exists(path)) {
k.response.statusCode(404)
return { error: "File not found" }
}
k.response.file(path, "application/pdf", "report-2024.pdf")
})binary()
Send a binary byte-array response. When filename is provided, Kooboo sets Content-Disposition: attachment;filename=....
| Parameter | Type | Required | Description |
|---|---|---|---|
contentType | string | Yes | Response Content-Type |
bytes | number[] | Yes | Binary byte array |
filename | string | No | Download filename |
Returns: void.
k.api.get("download-txt", () => {
const bytes = [75, 111, 111, 98, 111, 111] // "Kooboo"
k.response.binary("text/plain", bytes, "hello.txt")
})statusCode()
Set the HTTP status code.
| Parameter | Type | Required | Description |
|---|---|---|---|
code | number | Yes | HTTP status code |
Returns: void.
k.api.get(() => {
k.response.statusCode(404)
return "Not Found"
})unauthorized()
Set the HTTP status code to 401 (leaves the response body empty unless you write content explicitly).
Parameters: None.
Returns: void.
k.api.get(() => {
k.response.unauthorized()
})
// HTTP status code: 401, empty bodynotFound()
Set the HTTP status code to 404.
Parameters: None.
Returns: void.
k.api.get(() => {
k.response.notFound()
})redirect()
Redirect to a target URL.
| Parameter | Type | Required | Description |
|---|---|---|---|
url | string | Yes | Target URL |
absolute | boolean | No | Whether the URL uses an absolute or non-HTTP scheme |
Returns: void.
// Example API URL: /api/go/{action}
// Relative path
k.api.get("relative", () => {
k.response.redirect("/login")
})
// Absolute URL
k.api.get("external", () => {
k.response.redirect("https://example.com")
})
// Custom URI scheme (e.g. WeChat deep link)
k.api.get("wechat", () => {
k.response.redirect("wechat://kooboo.com", true)
})setHeader()
Set a custom HTTP response header.
| Parameter | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Response header name |
value | string | Yes | Response header value |
Returns: void.
k.api.get(() => {
k.response.setHeader("X-Custom-Header", "value")
k.response.setHeader("Access-Control-Allow-Origin", "*")
return "ok"
})execute()
Execute another site Page URL or an external http(s):// URL and append its output to the current response.
- Relative site URLs (such as
"/another-page"): resolve and render site Page resources only;k.api/ Code routes are not supported (passing an/api/...route finds no Page and silently writes nothing). Use ESimportin Module scripts to share logic across APIs. - Full
http:///https://URLs: perform an outbound HTTPGETrequest viaCurland write the returned body into the current response.
| Parameter | Type | Required | Description |
|---|---|---|---|
url | string | Yes | Site Page URL or external http(s):// URL to execute |
Returns: void.
// Example API URL: /api/exec/{action}
// 1. Relative site URL: renders a Page resource (does not invoke k.api routes)
k.api.get("render-page", () => {
k.response.execute("/another-page")
k.response.write("<!-- appended -->")
})
// 2. http(s):// URL: fetches the remote URL via Curl GET and appends its body
k.api.get("proxy", () => {
k.response.execute("https://example.com/snippet.html")
})stop()
Mark downstream page/template rendering as cancelled (RenderCancelled). It does not abort execution of subsequent JavaScript statements in the same callback (a following return still executes in an API handler; use JS return to exit early).
Parameters: None.
Returns: void.
<!-- Stop remaining page template output after emitting a custom response -->
<script env="server">
k.response.write("custom output")
k.response.stop()
</script>Common Usage
CORS Cross-Origin Configuration
CORS response headers are handled by the platform:
- Single API: set
cors: trueon the object managed by k.site.codes. - Whole site: enable CORS (
enableCORS) in Site Settings → Access Control.
When either is enabled, the platform sets Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, and Access-Control-Allow-Credentials. Note how OPTIONS preflight requests differ:
- Site-wide
enableCORSenabled: Kooboo short-circuitsOPTIONSpreflight requests, bypassing script body execution and site auth checks before returning CORS headers. - Only per-API
cors: trueenabled (enableCORSoff): top-level script statements still execute onOPTIONSrequests (thoughk.api.get/post/put/deletecallbacks do not matchOPTIONS) before CORS headers are added, and site auth guards are not bypassed automatically.
Call k.response.setHeader when you want to override a specific header; the platform preserves headers you set explicitly:
k.api.get(() => {
k.response.setHeader("Access-Control-Allow-Origin", "https://example.com")
return { ok: true }
})File Download
k.api.get("download", () => {
const filePath = "exports/data.csv"
if (!k.file.exists(filePath)) {
k.response.statusCode(404)
return { error: "File not found" }
}
k.response.file(filePath, "text/csv", "export.csv")
})TypeScript Definitions
interface Response {
meta: PageMeta;
write(value: any): void;
setHeader(key: string, value: string): void;
redirect(url: string, absolute?: boolean): void;
json(value: any): void;
executeView(ViewNameOrId: string): void;
renderViewAsString(ViewNameOrId: string): string | null;
binary(contentType: string, bytes: number[]): void;
binary(contentType: string, bytes: number[], filename?: string): void;
file(path: string, contentType?: string, fileName?: string): void;
statusCode(code: number): void;
unauthorized(): void;
notFound(): void;
execute(url: string): void;
stop(): void;
}
interface PageMeta {
title: string;
setMeta(Name: string, content: string): void;
setMeta(Name: string, HttpEquiv: string, CharSet: string, content: string): void;
setCustomerHeader(HeaderString: string): void;
getMeta(Name: string): MetaItem;
}
interface MetaItem {
name: string;
content: string;
httpEquiv: string;
charSet: string;
property: string;
}