- Documentation
- Server functions
- fetchRemote
Function
fetchRemote
Sends an HTTP or HTTPS request and passes the response to a callback without blocking the server. With postData it makes a POST request, without it a GET. The function gets the response body and a code: 0 = success, the HTTP status number on a server error, -1 when there is no connection or it timed out.
Syntax
bool fetchRemote(string url, function callback [, string postData, int timeoutMs = 10000])Arguments
urlstring- An
http://orhttps://address. callbackfunctionfunction(responseData, errno).postDatastring, optional- The POST request body.
timeoutMsint, optional = 10000- Timeout in ms (1000-60000).
Returns
true if the request started.
Example
Fetching a rate from a public API and showing it in chat.
fetchRemote("https://api.example.com/kurs.json", function(data, errno)
if errno ~= 0 then
outputServerLog("Błąd zapytania: " .. errno)
return
end
local info = fromJSON(data)
outputChatBox("Kurs: " .. tostring(info and info.rate))
end)
Notes
Argument order. The callback is the second argument and the POST data the third. The function gets two arguments: the body and the error code.
See also
callRemoteCalls a function exposed by another server over HTTP (arguments go as JSON in a POST request). In the current server version the function does not send the request and returnsfalse; usefetchRemotewithtoJSONinstead.abortRemoteRequestAborts a running HTTP request. In the current server version it cannot be aborted yet: the function returnsfalsewith a warning, and the request ends by itself after thefetchRemotetimeout.fromJSONReads JSON text and returns a Lua value. A top-level array (the waytoJSONwrites) unpacks into several results. Broken JSON givesniland a warning with the error position.