node.jscurlhttprequestfastly

recreating cURL request with -I, -H flags in nodeJS


On the command line, I can do a request like: curl -I -H "Fastly-Debug: 1"

and it will return a lot of helpful information from the CDN serving that URL, in this case, Fastly:

cache-control: public, max-age=0, must-revalidate
last-modified: Tue, 20 Apr 2021 21:17:46 GMT
etag: "4c5cb3eb0ddb001584dad329b8727a9a"
content-type: text/html
server: AmazonS3
surrogate-key: /v3.6/tutorial/nav/alerts-and-monitoring/
accept-ranges: bytes
date: Fri, 30 Apr 2021 20:50:15 GMT
via: 1.1 varnish
age: 0
fastly-debug-path: (D cache-lga21923-LGA 1619815815) (F cache-lga21940-LGA 1619815815)
fastly-debug-ttl: (M cache-lga21923-LGA - - 0)
fastly-debug-digest: 04c3e527819b6a877de6577f7461e132b97665100a63ca8f667d87d049092233
x-served-by: cache-lga21923-LGA
x-cache: MISS
x-cache-hits: 0
x-timer: S1619815815.944515,VS0,VE136
vary: Accept-Encoding
content-length: 65489

How can I do this in node?

This is my attempt:

const headers = {
  'Fastly-Key': environment.getFastlyToken(),
  'Accept': 'application/json',
  'Content-Type': 'application/json', 
  'Fastly-Debug': 1
};

async retrieveSurrogateKey(url) {
  console.log("this is the url: ", url)
  try {
    request({
      method: `GET`,
      url: url,
      headers: headers,
   }, function(err, response, body) {
     if (err){
       console.trace(err)
     }
     console.log(request.headers)

 })
  } catch (error) {
    console.log("error in retrieval: ", error)
  }
}

Is there a way for me to pass in the -I and -H flags?


Solution

  • The -H (header) flag allows you to specify a custom header in cURL. Your code already does this - great! All that's left is emulating the -I (head) flag.

    From cURL manpage for the -I option:

    Fetch the headers only! HTTP-servers feature the command HEAD which this uses to get nothing but the header of a document.

    To use the HEAD method, you need to specify it instead of GET:

    method: `HEAD`
    

    And finally, the headers returned by the server in the response can be obtained from response.headers.