Quantcast
Viewing all articles
Browse latest Browse all 24

Answer by mikemaccana for Where is the body in a nodejs http.get response?

Edit: replying to self 6 years later

The await keyword is the best way to get a response from an HTTP request, avoiding callbacks and .then()

You'll also need to use an HTTP client that returns Promises.http.get() still returns a Request object, so that won't work.

  • fetch is a low level client, that is both available from npm and nodeJS 17 onwards.
  • superagent is a mature HTTP clients that features more reasonable defaults including simpler query string encoding, properly using mime types, JSON by default, and other common HTTP client features.
  • axios is also quite popular and has similar advantages to superagent

await will wait until the Promise has a value - in this case, an HTTP response! Modern JS supports await top level too, so you can skip needing async function wrappers.

import superagent from "superagent";const response = await superagent.get("https://www.google.com");console.log(response.text);

Using await, control simply passes onto the next line once the promise returned by superagent.get() has a value.


Viewing all articles
Browse latest Browse all 24

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>