I have 2 routes test_01 and test_02. When request comes to test_02 route, How do i access route test_01 and get its response data?
I'm not talking about forwarding route from test_02 to test_01
server.route({
method: 'GET',
path: '/data/test_01',
handler: function (request, reply) {
reply('test_01')
}
})
server.route({
method: 'GET',
path: '/data/test_02',
handler: function (request, reply) {
// Get data from route '/data/test_01'
var test_01_data = ''
reply(test_01_data)
}
})
Controller
Index = function () {}
Index.prototype = {
test_01 : function (req, reply, data) {
reply('test_01')
},
test_02 : function (req, reply, data) {
reply('test_02')
}
}
module.exports = Index
Have a separate controller function to be called from the handlers
var controllerfn = function(req,reply){
//do stuff
return 'test_01';
};
Call it as required
server.route({
method: 'GET',
path: '/data/test_01',
handler: function (request, reply) {
reply(controllerfn(request,reply);
}
})
server.route({
method: 'GET',
path: '/data/test_02',
handler: function (request, reply) {
// Get data from route '/data/test_01'
var test_01_data = controllerfn(request,reply);
reply(test_01_data)
}
})
If you want to reuse that route and not make another socket connection you can inject to the other route.
server.route({
method: 'GET',
path: '/data/test_01',
handler: function (request, reply) {
reply('test_01')
}
})
server.route({
method: 'GET',
path: '/data/test_02',
handler: function (request, reply) {
// Get data from route '/data/test_01'
request.server.inject({
url: {
pathname: '/data/test_01'
}
}, (res) => {
var test_01_data = res.result;
return reply(test_01_data);
})
}
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.