Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท HTTP, HTTPS, net, TLS, dgram and dns

Node.js http.get() method

Reference for http.get() in Node.js: a shortcut for GET requests that calls end() for you, how to read the response, and when to choose fetch instead.

http.get() is http.request() with the method fixed to GET and req.end() already called. It takes the same arguments, returns the same http.ClientRequest, and delivers the response through the same 'response' event or callback. Because a GET request has no body, there is nothing left for you to write.

The shortcut saves one line, but it is still the low-level API: the response is a stream that you must read, errors arrive as events, and nothing is parsed for you.

NODE
http.get('http://127.0.0.1:3000/', (res) => {
  res.resume();
});

Try it

Node.js Reading a GET response

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js A small promise wrapper and a status check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
http.get(options[, callback])
http.get(url[, options][, callback])
// returns http.ClientRequest (already ended)
Name Description
url A string or URL for the target.
options The same options as http.request(). method is forced to 'GET' even if you set another one.
callback One-time listener for 'response'; receives an http.IncomingMessage.

Returns: the ClientRequest. Use it to attach 'error' or 'timeout' listeners or to call destroy().

Errors: invalid arguments throw synchronously. Connection problems are emitted as 'error' on the returned request.

Usage notes

  • Attach 'error' to the returned request. The return value is the request, not the response, so chaining .on('error', ...) is the idiom.
  • Always consume or discard the response. Read it, pipe it, or call res.resume(); otherwise the socket stays occupied and your program may never exit.
  • http.get() does not follow redirects. A 301 or 302 arrives as a normal response with a Location header.
  • Compressed bodies are not decoded. Node does not add Accept-Encoding for you and does not decompress; fetch() handles gzip, deflate and br.
  • No status check. res.statusCode of 404 or 500 is still a successful callback; check it yourself, as in the second example.
  • Prefer fetch() for application code when you want promises and JSON helpers; keep http.get() for tests, scripts with no dependencies, and cases that need an agent or raw socket control.
  • HTTPS: https.get() has the same shape.