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.
http.get('http://127.0.0.1:3000/', (res) => { res.resume(); });
Try it
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.
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
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. A301or302arrives as a normal response with aLocationheader.- Compressed bodies are not decoded. Node does not add
Accept-Encodingfor you and does not decompress;fetch()handlesgzip,deflateandbr. - No status check.
res.statusCodeof404or500is still a successful callback; check it yourself, as in the second example. - Prefer
fetch()for application code when you want promises and JSON helpers; keephttp.get()for tests, scripts with no dependencies, and cases that need an agent or raw socket control. - HTTPS:
https.get()has the same shape.