繁体   English   中英

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)
  }
})

如果要重用该路由而不进行另一个套接字连接,则可以注入其他路由。

  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);
          })
      }
  })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM