lua-nginx-module icon indicating copy to clipboard operation
lua-nginx-module copied to clipboard

Problem with post request reading in balancer_by_lua_block

Open bourne-3 opened this issue 1 year ago • 2 comments

hi the openresty version of mine is 1.13

I encountered a problem. When I am in the balance_by_lua stage, without ngx.req.read_body(), I can use the get_post_args function to read the parameters of the post; but in the access_by_lua stage, an error will appear; Why is get_post_args() can be used normally in the balance_by_lua stage without ngx.req.read_body()? 

tips:
	1、It has been confirmed that lua_need_request_body is not turned on

	2、ngx.req.read_body() is not read in other stages.

reproduction on the case:

upstream hash-forward {
    server 0.0.0.1;  

    balancer_by_lua_block {
        local ngx = require "ngx"
        local cjson = require "cjson.safe"
        local method = ngx.var.request_method

        if method == "POST" then
            local post_args, err = ngx.req.get_post_args()
            if not post_args then
                ngx.log(ngx.ERR, "failed to get post args: ", err)
                return ngx.exit(500)
            end
            local post_str = cjson.encode(post_args)
            
            ngx.log(ngx.ERR, "post params: " .. post_str)
        end

        local balancer = require "ngx.balancer"
        local ok, err = balancer.set_current_peer("127.0.0.1", 8088)
        if not ok then
            ngx.log(ngx.ERR, "failed to set the current peer: ", err)
            return ngx.exit(500)
        end
    }

    keepalive 500;  # connection pool
}

bourne-3 avatar Feb 29 '24 12:02 bourne-3

For this kind of question about why it is able to work, I think you should delve into the code to analyze the problem.

zhuizhuhaomeng avatar Mar 01 '24 01:03 zhuizhuhaomeng

You required to read POST argument in balancer_by_lua*.

As per documentation, ngx.req.read_body() is not available in the balancer_by_lua*

In order to access body value in the balancer_by_lua, it is suggested to read required value in the rewrite_by_lua* or access_by_lua* phase and store value in the ngx.ctx i.e request context.

you can access ngx.ctx in the balancer_by_lua* and take required operation

ankitsharma5652 avatar Mar 23 '24 18:03 ankitsharma5652