Context
Context is an object which contains the parsed data from the current request.
This object is passed in the request handler as an argument.
// Here we return the pathapp.get('/context', (ctx) => ctx.body(ctx.path));
Path
The context includes the parsed request pathname and the start and end indices of the pathname.
// The full url is http://localhost:3000/context/middle/end// The path starts at 21 and ends at 40// So the full sentence should be: "Hey, these are the path, start of the path and the end of it: /context/middle/end, 21, 40"app.get('/context/middle/end', (ctx) => ctx.body( `Hey, these are the path, start of the path and the end of it: ${ctx.path}, ${ctx.pathStart}, ${ctx.pathEnd}`));
Parameters
The context includes parsed parameters from the request URL.
// Upon visiting http://localhost:3000/context/parameters/apple// We get back: "This is a parameter: apple"app.get( '/context/parameters/:name', (ctx) => ctx.body(`This is a parameter: ${ctx.params.name}`));
Request
The context includes the original Request
object.
// To see a visible response, send a POST request to http://localhost:3000/context/request// We will send the following JSON: {"message":"Hey"}// The response should be the exact same JSON returnedapp.post( '/context/request', async (ctx) => ctx.json(await ctx.req.json()));
Response methods
The context includes methods to return a response object.
// Send a response with the provided BodyInit (text, streams, typed arrays, ...)ctx.body('Hi');
// Shorthand of `ctx.body(null)` - return a response with empty bodyctx.end();
// Send HTML responsectx.html('<p>Hi</p>');
// Send JSON payloadctx.json({ hello: 'world' });
// Redirection (statusCode can be 301, 302, 307 or 308)ctx.redirect(location, statusCode);
You can add headers, set the status code and text of the response:
app.get('/context/headers/and/status', (ctx) => { // Set the status ctx.status = 200;
// Add a new header key-value pair ctx.headers.push(['X-Powered-By', 'byte']);
// Send back response with headers and status code return ctx.html('<h1>Hi</h1>');});