OpenResty - 使用 lua 进行 http 调用时没有响应

OpenResty - No response when making a http call with lua

当从我的 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\"

谢谢丹尼

no resolver defined to resolve "www.google.de"

您需要配置 resolver:

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

In case of domain names, this method will use Nginx core's dynamic resolver to parse the domain name without blocking and it is required to configure the resolver directive in the nginx.conf file like this:

resolver 8.8.8.8;  # use Google's public DNS nameserver

Why do I get a 200 response instead of 500

您应该调用 ngx.exit 来中断请求的执行和 return 状态代码。

替换

return ngx.HTTP_INTERNAL_SERVER_ERROR

ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)