The reply.action
has a special purpose: to initiate some actions or requests serverdata - it is meant to deal with AJAX-requests
. The server does not reply a view, but takes some actions and returns proper data.
The reply.action takes 5 arguments: 'request’, 'reply’, 'options’, 'language’, 'manifest’.
actions
is the name of the action-file which should be defined inside the actions-folder
. options
are additional options (object) that the action-file receives trhough the router. The action-file should be a commonjs
-module with this signature:
Setting up reply.action inside routes.js
'use strict';
let routes = [
{
method: 'PUT',
path: '/action-url',
handler: function (request, reply) {
const options = {};
reply.action('actionname', options);
}
}
];
module.exports = routes;
Example action-module /actions/actionname.js
const actionFn = (request, reply, options, language, manifest) => {
return {
status: 'OK'
};
};
module.exports = actionFn;
Note that the module needs to return a function
that will be invoked by 5 arguments. Whatever the action-function returns, will be used to reply the request.
Asynchronous action-files
Often, you will need to perform an asynchronous action, before replying the request. If the action-function returns a Promise
, then the reply will happen as soon as the Promise gets resolved, replying the Promise-result:
Example asynchronous action-module
const actionFn = async (request, reply, options, language, manifest) => {
await doSomeAsyncStuffToWaitFor();
return {
status: 'OK'
};
};
module.exports = actionFn;
Note that if the Promise gets rejected, the server will response with a 500-error holding the rejected error-value. If you want to prevent this, you should catch the error inside the action-module:
Example asynchronous action-module that never errors
const actionFn = async (request, reply, options, language, manifest) => {
let status, message;
try {
await doSomeAsyncStuffToWaitFor();
status = 'OK';
}
catch (err) {
status = 'ERROR',
message = err.message;
}
return {
status,
messsage
};
};
module.exports = actionFn;