JSON, Text & XML¶
Send structured or plain-text HTTP bodies with json(), text(), xml(), or the generic send(). Pick the method that matches what your caller expects.
json(obj)¶
Sets Content-Type: application/json and sends JSON. The workhorse for API responses.
String passthrough — if you pass a string, it is sent as-is (useful for pre-serialized JSON):
Serialization errors — if JSON.stringify fails, res returns 500 with:
Circular references are JavaScript's way of saying "nice try."
text(content)¶
Sets Content-Type: text/plain and sends plain text.
If the string contains EJS tags (<%), it is rendered first:
xml(content)¶
Sets Content-Type: application/xml and sends the body unchanged.
send(body)¶
Generic send method. Uses whatever Content-Type you set with set(), or auto-detects HTML when the body looks like HTML.
For HTML bodies, send() applies the same HTML access protection as html(). Prefer html() or json() when the content type is known.
Try it — copy-paste examples¶
JSON API with validation¶
let id = params.id
if (!id) {
return res.status(400).json({ error: "id required" })
}
let record = await db.bot.get("records:" + id)
res.json({ ok: true, record })
Plain-text health check¶
XML feed snippet¶
let items = await db.bot.get("feed") || []
let xml = '<?xml version="1.0"?><rss><channel>'
for (let item of items) {
xml += `<item><title>${item.title}</title></item>`
}
xml += "</channel></rss>"
res.xml(xml)
See also¶
- HTML & EJS — templated HTML responses
- res.render() — serve another command (e.g.
api.json) - Headers & Status