Fetch client
`toonFetch`, `configureToonAxios`, and `createToonAxios` examples
`toonkit2` provides a lightweight fetch wrapper and axios helpers that automatically handle TOON serialization and parsing, plus convenience token handling.
Basic GET
import { toonFetch } from "toonkit2"; const res = await toonFetch("https://localhost:3000/users"); console.log(res.data);
GET with headers
const res = await toonFetch("https://localhost:3000/users", { headers: { Authorization: "Bearer token123", "x-api-key": "abc123" } }); console.log(res.data);
Token shortcut
Pass `token` as a string or function — it's added as `Authorization: Bearer ...`.
const res = await toonFetch("https://localhost:3000/users", { token: "mytoken" }); // header => Authorization: Bearer mytoken
const res = await toonFetch("https://localhost:3000/profile", { token: () => localStorage.getItem("jwt") });
POST — TOON body (default)
By default, providing `data` will serialize to TOON and set `Content-Type: application/toon`.
await await toonFetch("https://localhost:3000/users", { method: "POST", data: { name: "Manoj", age: 22 } });
POST — send JSON instead
Override `Content-Type` to `application/json` to send JSON payloads.
await await toonFetch("https://localhost:3000/users", { method: "POST", headers: { "Content-Type": "application/json" }, data: { name: "Manoj" } });
Full example (headers + token + body)
const res = await toonFetch("https://localhost:3000/create-user", { method: "POST", token: "jwt_token_here", headers: { "x-app": "toonkit2" }, data: { username: "manoj", email: "manoj@gmail.com" } }); console.log(res.data);
Configure global base URL
import { configureToonAxios } from "toonkit2"; configureToonAxios({ baseURL: "https://api.example.com", token: () => localStorage.getItem("token") }); // now: await toonFetch('/users') -> https://api.example.com/users
Create a separate axios client
import { createToonAxios } from "toonkit2"; const api = createToonAxios({ baseURL: "https://api.example.com", token: "abc123" }); const users = await api.get("/users"); console.log(users.data);
Response format
toonFetch returns an object{ data, response } wheredata is already parsed JS (TOON or JSON) and response is a Fetch-like `Response` wrapper.
const { data, response } = await toonFetch("/users");
console.log(data);
console.log(response.status);Example Express backend
A simple Express route that accepts TOON text and returns a TOON response.
app.post("/users", express.text(), (req, res) => { console.log(req.body); // TOON string res.setHeader("Content-Type", "application/toon"); res.send('name[1]{0:s}: Manoj age[1]{0:n}: 22'); });
Real usage example (login)
const login = async () => { const { data } = await toonFetch("/login", { method: "POST", headers: { "Content-Type": "application/json" }, data: { email: "manoj@gmail.com", password: "123456" } }); console.log(data); };