Reading request body in custom plugin


#1

I am trying to read request body in a custom plugin

  local data = kong.request.get_body()
  if data then
      kong.log(data)
  end

I am getting the following error

2019/03/14 21:57:55 [error] 14039#0: *45 lua entry thread aborted: runtime error: /usr/local/share/lua/5.1/kong/pdk/private/phases.lua:66: no phase in kong.ctx.core.phase
stack traceback:
coroutine 0:
        [C]: in function 'error'
        /usr/local/share/lua/5.1/kong/pdk/private/phases.lua:66: in function 'check_phase'
        /usr/local/share/lua/5.1/kong/pdk/request.lua:594: in function 'get_body'
        .../Apps/troop/kong/plugins/customlog/handler.lua:72: in function <.../Apps/troop/kong/plugins/customlog/handler.lua:62>, context: ngx.timer, client: 127.0.0.1, server: 0.0.0.0:8000

Can anyone help me understand the problem here? I need to log the request body in my plugin.


#2

Looking at that error I’m going to guess that your code currently sits within the new() method in your plugin code. This is executed before the request context is available. Try moving your code to the appropriate phase handler (e.g. access) and it should work. E.g.

function PluginHandler:access(conf)
  PluginHandler.super.access(self)

  local data = kong.request.get_body()
  if data then
      kong.log(data)
  end

  return kong.response.exit(200)
end

See https://docs.konghq.com/1.0.x/plugin-development/custom-logic/#available-request-contexts for more information on the execution life-cycle (phases).


#3

Thanks @onematchfox

I was calling kong.request.get_body() in the :log handler