使用nginx获取get/post参数值并返回给客户端

使用nginx获取get/post参数值并返回给客户端

1.需求

获取http get或post参数的值,拼成json格式,返回给客户端。

2.思路

使用nginx lua中的ngx.req.get_post_args()获取post中的arg的值,使用ngx.var.arg_PARAMETER获取get中PARAMETER的值;

使用ngx.say()返回参数值。

3.实现

配置文件(只写出location部分):

...    location /response {        lua_need_request_body on;        default_type application/json;        content_by_lua_file conf/test/response.lua;    }...

response.lua:

local xxxIdArgs = ""local my_xxxId = ""local my_uri = ngx.var.urilocal postArgs, err = ngx.req.get_post_args()-- Get xxxId from post contentfor key, val in pairs(postArgs) do      if key == "xxxId" then            if  val ~= nil then                  my_xxxId = val            end             xxxIdArgs = '{"xxxId":"'  .. my_xxxId .. '"}'            ngx.say(xxxIdArgs)            return                  endend-- Get xxxId from get argsif ngx.var.arg_xxxId ~= nil then      my_xxxId = ngx.var.arg_xxxIdendxxxIdArgs = '{"xxxId":"' .. my_xxxId .. '"}'ngx.say(xxxIdArgs)

4. 注意

本来想使用nginx自带的return命令,但是官网介绍return运行在rewrite阶段,意思是说,还没到获取参数的阶段,return就已经返回了,所以参数的值肯定为空。

关于nginx及nginx lua的各个执行阶段,参看:

http://blog.csdn.net/yangguanghaozi/article/details/54139258

免责声明:本网信息来自于互联网,目的在于传递更多信息,并不代表本网赞同其观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,并请自行核实相关内容。本站不承担此类作品侵权行为的直接责任及连带责任。如若本网有任何内容侵犯您的权益,请及时联系我们,本站将会在24小时内处理完毕。
相关文章
返回顶部