Define route options in app.js:
var server = require('@nodedk/server')
server({
port: 3000,
routes: [
{
name: 'subscribe', // Used by state.link('subscribe')
paths: '/subscribe', // Exact path, array, language map, or '*'
methods: 'POST', // String or array; defaults to GET
// Before this route's middleware and handler
before: function (state) {
console.log('Subscription request received')
},
// Functions run in order
middleware: [
function (state) {
state.data.source = 'website'
}
],
// Validates state.req.body.params before the handler
schema: {
email: { required: true, is: 'email' }
},
// Produces the response
handler: function (state) {
return state.jarpc({ ok: true })
},
// After the handler
after: function (state) {
state.res.setHeader('x-source', state.data.source)
},
// Set the result explicitly when an error occurs
error: function (state) {
console.error(state.err)
state.res.statusCode = 500
state.result = { ok: false, message: 'Please try again' }
},
// After response handling; not awaited
done: function (state) {
console.log('Subscription request finished')
}
}
]
})
GET includes HEAD. Keep each path on one route.
See Server options for the surrounding server configuration.
Next: State properties →