navin
navin

Reputation: 185

Kong API Gateway - Reading request body in custom plugin

I am trying to read the request body in a custom plugin by following this url

  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.

Can anyone help me understand the problem here?

I need to log the request body in my plugin.

Upvotes: 1

Views: 3146

Answers (1)

Xanagandr
Xanagandr

Reputation: 763

That call can only be called in the "rewrite, access or admin_api" phase.

Looking at your log output, the context you're trying to call it is ngx.timer, which is not even wrapped by Kong as one of its contexts. (More on that here)

What you could do is call "kong.request.get_body()" in a phase that can call it, store it in a temp var (using "kong.ctx.plugin" object), and then use it in the "log" phase for said plugin.

Upvotes: 1

Related Questions