ngx.req和get/post参数获取,ngx.reqpost


ngx.req.raw_header 和ngx.req.get_headers示例

(1)ngx.req.raw_header
函数原型: headers = ngx.req.get_headers(max_headers?, raw?)
返回值类型为table,其大概的内容如下:

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding:gzip, deflate, br
Accept-Language:zh-CN,zh;q=0.8,en;q=0.6
Cache-Control:max-age=0
Connection:keep-alive
Host:localhost:8080
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36

(2)ngx.req.get_headers
函数原型:str = ngx.req.raw_header(no_request_line?)
返回值类型为是string,其大概的内容如下:

GET /echo/cyrus HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
Upgrade-Insecure-Requests: 1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.8,en;q=0.6

以上内容因使用的web client不同,输出的内容也有较大的差异,但是一些基本的信息和格式大致是相同的。
在使用中,一般都可以通过特定的函数获取到指定的内容,比如host/uri/method/http_version等。

ngx.req.get_uri_args 和 ngx.req.get_post_args示例

(1)ngx.req.get_uri_args
函数原型:args = ngx.req.get_uri_args(max_args?)
返回类型为table,可以使用以下方式遍历:

for key, val in pairs(args) do
...
end

注意只能获取?后面的变量和相应的值,比如location为location ~ /echo/(.*)
http://localhost:8080/echo/cyrus?name&age=2
输出的结果为:

hello, cyrus
age:2
name:true

无法获取到path Variable的变量和值。对于path variable的获取使用以下方式:
ngx.say("hello, ",ngx.var[1])
注意这里的下标是从1开始。
(2)ngx.req.get_post_args
函数原型:args, err = ngx.req.get_post_args(max_args?)
返回值类型为table,遍历方式同(1)。其请求的方式为:
curl --data 'foo=bar&bar=baz&bar=blah' localhost/test
结果为:

foo: bar
bar: baz, blah

注意这里可以多次定义同一个key(比如bar),解析时作为一个可以有多个值,且使用逗号进行分割。Web使用json格式发送post请求更为常见,这里就可以使用ngx.req.get_body_data
(3)ngx.req.get_body_data
函数原型:data = ngx.req.get_body_data()
返回值类型为string,对于接收到的字符串可以进行json解码,从而实现json参数的传递。

相关内容

    暂无相关文章