openresty 前端開發入門二

這一章主要介紹介紹怎麼獲取請求參數,而且處理以後返回數據

咱們知道http請求一般分爲兩種,分別是GET,POST,在http協議中,GET參數一般會緊跟在uri後面,而POST請求參數則包含在請求體中,nginx默認狀況下是不會讀取POST請求參數的,最好也不要試圖使改變這種行爲,由於大多數狀況下,POST請求都是轉到後端去處理,nginx只須要讀取請求uri部分,以及請求頭html

因爲這樣的設計,因此獲取請求參數的方式也有兩種nginx

GETgit

local args = ngx.req.get_uri_args() -- 這裏是一個table,包含全部get請求參數
local id = ngx.var.arg_id -- 這裏獲取單個請求參數,可是若是沒有傳遞這個參數,則會報錯,推薦上面那張獲取方式

POSTgithub

ngx.req.read_body() -- 先讀取請求體
local args = ngx.req.get_post_args() -- 這裏也是一個table,包含全部post請求參數

能夠經過下面這個方法獲取http請求方法web

local request_method = ngx.var.request_method -- GET or POST

爲了統一獲取請求參數的方式,隱藏具體細節,提供一個更友好的api接口,咱們能夠簡單的封裝一下後端

lua/req.luaapi

local _M = {}

-- 獲取http get/post 請求參數
function _M.getArgs()
    local request_method = ngx.var.request_method
    local args = ngx.req.get_uri_args()
    -- 參數獲取
    if "POST" == request_method then
        ngx.req.read_body()
        local postArgs = ngx.req.get_post_args()
        if postArgs then
            for k, v in pairs(postArgs) do
                args[k] = v
            end
        end
    end
    return args
end

return _M

這個模塊就實現了參數的獲取,並且支持GET,POST兩種傳參方式,以及參數放在uri,body的post請求,會合並兩種方式提交的參數post

接下來咱們能夠寫一個簡單的lua,來引入這個模塊,而後測試一下效果測試

conf/nginx.confui

worker_processes  1;

error_log logs/error.log;

events {
    worker_connections 1024;
}

http {
    lua_package_path /Users/Lin/opensource/openresty-web-dev/demo2/lua/?.lua;  # 這裏必定要指定package_path,不然會找不到引入的模塊,而後會500
    server {
        listen 80;
        server_name localhost;
        lua_code_cache off;
        location ~ /lua/(.+) {
            default_type text/html;    
            content_by_lua_file lua/$1.lua;
        }
    }
}

lua/hello.lua

local req = require "req"

local args = req.getArgs()

local name = args['name']

if name == nil or name == "" then
    name = "guest"
end

ngx.say("<p>hello " .. name .. "!</p>")

測試

http://localhost/lua/hello?na...
輸出 hello Lin!
http://localhost/lua/hello

輸出 hello guest!

ok 到這裏,咱們已經可以根據請求的參數,而且在作一下處理後返回數據了

示例代碼 參見demo2部分

相關文章
相關標籤/搜索