Nginx ruft intern eine andere Anfrage auf und gibt die Anfragedaten zurück

Nginx ruft intern eine andere Anfrage auf und gibt die Anfragedaten zurück

Ich verwende Nginx und Lua, um meine Rest-API zu analysieren (https://openresty-reference.readthedocs.io/en/latest/Lua_Nginx_API/). Ich versuche, intern innerhalb meines Rest-Aufrufs eine andere API aufzurufen, die ein anderer Server ist, und diese Antwort zurückzugeben. Aber ich erhalte immer eine leere Antwort. Unten ist meine Konfiguration, ich bitte um /student, jede Hilfe ist sehr willkommen

location /student {
    content_by_lua '
    local str = "test"
    local res = ngx.location.capture("/detail",{method = ngx.HTTP_POST, body = str})
    ngx.say(str)
    ';
}
location /detail {
    set $target '104.28.17.1/post';
    set $pass 'Basic Y2l28=';
    lua_need_request_body on;
    content_by_lua '
    proxy_set_header          Host            $host;
    proxy_set_header          X-Real-IP       $remote_addr;
    proxy_set_header          X-Forwarded-For $proxy_add_x_forwarded_for;
    #access_by_lua '
    proxy_set_header Authorization $pass;
    proxy_set_header Content-Type 'application/x-www-form-urlencoded';
    proxy_set_header Accept '*/*';
    proxy_set_header Connection 'keep-alive';
    proxy_pass http://$target;
}

Antwort1

Sie können resty.http verwenden, um einen Aufruf in Lua durchzuführen und ihn in den Textkörper zu schreiben. Unten ein HTTPS-Aufruf mit Authentifizierung an eine API:

-- load requirements 
http = require "resty.http"

local function api_request(ip, api_host, api_hostname, api_cred, api_url)
  local httpc  = http.new()
  httpc:set_timeout(500)
  path = api_host .. string.format(api_url, ip)
  local response, err = httpc:request_uri(path,{
      method = "GET",
      headers = {
          ["Authorization"] ="Basic " .. api_cred,
          ["Host"] = api_hostname,
      },
      ssl_verify = false,
  })
  return response
end

verwandte Informationen