大叔问题定位分享(36)openresty(nginx+lua)中获取不到post数据,ngx.req.get_body_data返回nil

openresty(nginx+lua)中获取不到post数据,ngx.req.get_body_data返回nil

This function returns nil if

  • the request body has not been read,
  • the request body has been read into disk temporary files,
  • or the request body has zero size.

打开nginx调试日志

error_log /var/log/nginx/error.log debug;

发现如下日志:

2019/07/26 10:41:43 [warn] 319#319: *3041588 a client request body is buffered to a temporary file /usr/local/openresty/nginx/client_body_temp/0000001574, client: 192.168.0.2, server: localhost, request: "POST /test HTTP/1.1", host: "192.168.0.1"

可见是因为body太大,被缓冲到临时文件中,此时应该使用ngx.req.get_body_file

fix代码

function read_from_file(file_name)
  local f = assert(io.open(file_name, "r"))
  local string = f:read("*all")
  f:close()
  return string
end

ngx.req.read_body()
local body = ngx.req.get_body_data()
if (body == nil) then
  local body_file = ngx.req.get_body_file()
  if body_file then
    body = read_from_file(body_file)
  else
    ngx.status = 500
    ngx.say("error")
    return
  end
end

 

参考:
https://github.com/openresty/lua-nginx-module#ngxreqget_body_data

posted @ 2019-07-27 00:26  匠人先生  阅读(3380)  评论(1编辑  收藏  举报