Routing
Register routes with the Sponge methods, read parameters and understand how paths are matched.
Registering routes
Register routes with the Sponge methods. Each one takes a path, a handler and any number of route-specific middleware, and returns the app so calls can be chained.
TypeScript
bob .spongGet('/users', listUsers) .spongPost('/users', createUser) .spongPut('/users/:id', replaceUser) .spongPatch('/users/:id', updateUser) .spongDelete('/users/:id', deleteUser)| Method | HTTP verb |
|---|---|
spongGet(path, handler, ...middleware) | GET |
spongPost(path, handler, ...middleware) | POST |
spongPut(path, handler, ...middleware) | PUT |
spongPatch(path, handler, ...middleware) | PATCH |
spongDelete(path, handler, ...middleware) | DELETE |
spongHead(path, handler, ...middleware) | HEAD |
Route parameters and query strings
TypeScript
bob.spongGet('/users/:id', async (spongReq, spongRes) => { const { id } = spongReq.params // decoded automatically const page = spongReq.query.get('page') // URLSearchParams return spongRes.json({ id, page })})How paths are matched
- A route matches when it has the same number of segments as the request path.
:namesegments capture a value and decode it withdecodeURIComponent. A malformed encoding does not match.- A trailing slash is ignored, so
/users/reaches the/usersroute. - Static routes win over dynamic ones, whatever the registration order. With both
/users/meand/users/:idregistered, a request to/users/megoes to the static route.
TypeScript
// Both routes can live side by side, in any order.bob.spongGet("/api/tasks/me", controller.findMe, auth.middleware);bob.spongGet("/api/tasks/:id", controller.findOne, auth.middleware);Starting the server
TypeScript
bob.spongListen(4000, () => { console.log('RiserBob is running on http://localhost:4000')})spongListen(port = 4000, callback?) starts the server on Bun and returns it. The callback runs once the server is up.
When nothing matches
- No route for the path:
404 Not Found. - The path exists but not for that method:
405 Method Not Allowed, with anAllowheader listing the methods that do exist amongGET,POST,PUT,PATCHandDELETE.
OPTIONS requests
The server answers every OPTIONS request itself, with 204, before routing. When the request has an Origin header the answer carries the CORS preflight headers, so a browser preflight works without you registering a route.