openresty 中解析POST数据


openresty 中解析POST数据


使用带有lua模块的ngx_openresty, 可能需要获取POST数据。

标准POST body数据格式为'foo=bar&foo1=bar1', 如果body数据是json格式{"foo":"bar", "foo1":"bar1"}, 就需要另外的解析方式。

编译ngx_openresty时默认带有的cjson模块为我们提供了解析json数据的函数。

思路是:

  • 读取body数据
  • 当做json解析
  • json解析失败,则当做标准post数据解析

示例:
`

access_by_lua '

local cjson = require "cjson.safe"

ngx.req.read_body()

local body_str = ngx.req.get_body_data()

if not body_str then

    ngx.exit(ngx.HTTP_BAD_REQUEST)

end

local value, err = cjson.decode(body_str)

if not value then

    local value = ngx.req.get_post_args()

    -- value now is table 

    ngx.say("body is post data")

else

    ngx.say("body is post json")

end

';

`


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM