Hapi js从一条路线访问另一条路线
Hapi js accessing one route from another
我有 2 条路线 test_01 和 test_02。
当请求到达 test_02 路由时,如何访问路由 test_01 并获取其响应数据?
我不是在谈论从 test_02 到 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)
}
})
控制器
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
有一个单独的控制器函数可以从处理程序中调用
var controllerfn = function(req,reply){
//do stuff
return 'test_01';
};
按需调用
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)
}
})
如果您想重用该路由而不是建立另一个套接字连接,您可以inject到另一条路由。
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);
})
}
})
我有 2 条路线 test_01 和 test_02。 当请求到达 test_02 路由时,如何访问路由 test_01 并获取其响应数据?
我不是在谈论从 test_02 到 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)
}
})
控制器
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
有一个单独的控制器函数可以从处理程序中调用
var controllerfn = function(req,reply){
//do stuff
return 'test_01';
};
按需调用
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)
}
})
如果您想重用该路由而不是建立另一个套接字连接,您可以inject到另一条路由。
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);
})
}
})