If you need to implement a route that uses an HTTP method other than GET
, you can use an advanced route definition.
Example Usage
Defining a Route with a Custom HTTP Method
/index.server.js
import joystick from '@joystick.js/node';
joystick.app({
routes: {
'/': {
method: 'GET',
handler: (req = {}, res = {}) => {
return res.status(200).send('Howdy');
},
},
},
});
Instead of assigning a callback function directly to your route, assign an object. On that object, specify either:
- A single
method
option as astring
(one ofOPTIONS
,HEAD
,CONNECT
,GET
,POST
,PUT
,DELETE
, orPATCH
). - Or, to support multiple methods on a single route, a
methods
option as an array of HTTP methodstring
s.
Your route’s callback should be assigned to the handler
property. This behaves identically to a basic route definition.
Adding Route-Specific Middleware
/index.server.js
import joystick from '@joystick.js/node';
import custom_middleware from 'middleware-package';
joystick.app({
routes: {
'/': {
methods: ['POST', 'PUT'],
middleware: [
custom_middleware,
(req = {}, res = {}, next = {}) => {
if (!req.body) {
return res.redirect('/404');
}
next();
},
],
handler: (req = {}, res = {}) => {
return res.status(200).send('Howdy');
},
},
},
});
Advanced route definitions support a middleware
array for running route-specific middleware functions before the handler()
function.
API
Definition
{
[route_path: string]: {
method: string,
methods: array[string],
middleware: array[function],
handler: (req: object, res: object) => void,
}
}
Parameters
- route_path object required
-
The route path as a string, assigned an object for its definition. Either
method
ormethods
must be defined for the route to register.- method string
-
The HTTP method for the route (one of:
GET
,POST
,PUT
,PATCH
,DELETE
, orOPTIONS
). - methods array[string]
-
An array of HTTP methods as strings for the route (e.g.,
['GET', 'POST']
). - middleware array
-
An optional array of Express middleware functions to run before the route's
handler()
method. - handler function required
-
The callback function for the route. Receives the inbound
req
andres
objects.