【问题标题】:OpenResty - No response when making a http call with luaOpenResty - 使用 lua 进行 http 调用时没有响应
【发布时间】:2021-06-21 09:11:14
【问题描述】:

从我的 nginx 中向 url 发出请求时,此请求的响应始终不存在。好像没有发送请求。

这是我的 nginx.conf

worker_processes  1;
error_log logs/error.log;
events {
    worker_connections 1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" "$http_clientid"';

    access_log  logs/access.log  main;

    server {
        listen 8080;

        location /token-test {
          access_log logs/token.log main;

          content_by_lua_block {
            local cjson = require "cjson"
            local http = require "resty.http"
            local httpc = http.new()
            local ngx = ngx
            
            local res, err = httpc:request_uri("http://www.google.de", {method="GET"})

            if not res then
               ngx.say(cjson.encode({message = "Error getting response",status = ngx.HTTP_INTERNAL_SERVER_ERROR }))
               return ngx.HTTP_INTERNAL_SERVER_ERROR
            end

            return ngx.HTTP_OK
          }
        }
  }
}

我通过此响应正文获得 200 响应状态:

{
  "status": 500,
  "message": "Error getting response"
}

日志中没有错误。

为什么我得到的是 200 响应而不是 500,为什么响应正文包含来自不存在条件块的消息?

更新 我记录了错误: no resolver defined to resolve \"www.google.de\"

谢谢丹尼

【问题讨论】:

    标签: nginx lua openresty


    【解决方案1】:

    没有定义解析器来解析“www.google.de”

    你需要配置resolver:

    https://github.com/openresty/lua-nginx-module#tcpsockconnect

    如果是域名,此方法会使用 Nginx 核心的动态解析器​​来解析域名而不阻塞,需要在 nginx.conf 文件中配置解析器指令,如下所示:

    resolver 8.8.8.8;  # use Google's public DNS nameserver
    

    为什么我得到的是 200 而不是 500

    你应该调用ngx.exit来中断请求的执行并返回状态码。

    替换

    return ngx.HTTP_INTERNAL_SERVER_ERROR
    

    与

    ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
    

    【讨论】:

    • 缺少解析器是问题所在。谢谢帮助
    猜你喜欢
    • 2018-02-19
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 2019-10-25
    • 2015-09-28
    • 2019-02-07
    • 1970-01-01
    • 2012-01-28
    相关资源
    最近更新 更多