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