最近在码代码的过程中,调试时候发现lua下经常获取不到http请求的body,在官网翻了好多遍文案后有了一个总结,希望对lua开发的同学有些帮助
-- Require Modules
local conf = require "ik_config"
local cjson = require "cjson.safe"
local ngx_req_read_body = ngx.req.read_body
local ngx_req_get_body_data = ngx.req.get_body_data
local ngx_say = ngx.say
local _M = {}
_M._VERSION = '1.0.0'
-- enable check
local function resp()
ngx_req_read_body()
local body = ngx_req_get_body_data()
-- response data
ngx_say(cjson_encode({
["body"] = body,
["success"] = true,
["msg"] = ""
}))
end
重点是这两行
ngx_req_read_body()
local body = ngx_req_get_body_data() //这里获取到body,必须先调用上面ngx_req_read_body函数,才能拿到body的data
如不执行 ngx_req_read_body() 是拿不到请求的body