簡體   English   中英

模擬HEAD重定向請求(通過nock模塊)

[英]Mock a HEAD request for a redirect (via nock module)

在我的項目中,我嘗試擴展推文以使其完全顯示。 通過這種平和的代碼(找到@ stackoverflow)可以擴展由bit.ly短接的鏈接。

function expandUrl(shortUrl,callback) {
  debug("expandUrl");
  request( { method: "HEAD", url: shortUrl, followAllRedirects: true },
    function (error, response) {
      if (error) return callback(null,shortUrl);
      return callback(null,response.request.href);
    }
  );
}

為了在摩卡測試期間無需在線,我想使用以下代碼來修飾這部分代碼:

nock('http://bit.ly')
      .intercept("/1Ghc7dI","HEAD")
      .reply(200,undefined,{location:"http://discoverspatial.com/courses/qgis-for-beginners"});

但這是行不通的。 此作業完成后,response.request.href為“未定義”。 (我嘗試使用href而不是location,這沒有區別。

要進行重定向,您需要將狀態設置為HTTP URL重定向狀態,如@apsillers在評論中所述。 另外,如果您不希望在線,也需要對目標網址進行定位,因為request會調用它來檢查它是否不是重定向:

nock('http://bit.ly')
      .intercept("/1Ghc7dI","HEAD")
      .reply(301,undefined,{location:"http://discoverspatial.com/courses/qgis-for-beginners"});

nock('http://discoverspatial.com')
      .intercept("/courses/qgis-for-beginners", "HEAD")
      .reply(200,"OK");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM