首页 > 解决方案 > 在 nodeJS 中使用 -I、-H 标志重新创建 cURL 请求

问题描述

在命令行上,我可以执行如下请求: curl -I -H "Fastly-Debug: 1"

它会从为该 URL 提供服务的 CDN 中返回许多有用的信息,在本例中为 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

如何在节点中执行此操作?

这是我的尝试:

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)
  }
}

有没有办法让我传入 -I 和 -H 标志?

标签: node.jscurlhttprequestfastly

解决方案


( -Hheader) 标志允许您在 cURL 中指定自定义标头。您的代码已经这样做了 - 太棒了!剩下的就是模拟-I(head) 标志。

来自 -I 选项的 cURL 手册页:

仅获取标题!HTTP 服务器具有 HEAD 命令,它用于获取文档标题以外的任何内容。

要使用 HEAD 方法,您需要指定它而不是 GET:

method: `HEAD`

最后,服务器在响应中返回的标头可以从response.headers.


推荐阅读