可悲的是,大多數有關此問題的 Stack Overflow 答案/問題都使用了已棄用的請求庫。例如,我有一個 URL http://bitly.com/3eZyxM1(它重定向到https://google.com,然后重定向到https://www.google.com)。給定第一個 URL(有點),我怎么能找出它重定向到的第一個位置(不是最終位置,它到達的第一個位置,即https://google.com. 我很喜歡使用第三方npm庫,這么久因為它們沒有被棄用。理想情況下,它應該在 Node.js 16 或更高版本中作業。
uj5u.com熱心網友回復:
我最終使用了got 庫。我用npm install got.
我可以通過這樣做來使用它。它匯入庫,獲取(或got)URL,并獲取它重定向到的所有內容,然后.map僅用于獲取 URL 本身,而不是其他資訊。
import got from 'got'
got('http://bitly.com/3eZyxM1').then((res) => {
console.log(res.redirectUrls.map(url => url.href))
})
列印出重定向路徑(默認情況下,它提供了一堆關于 URL 的資訊,所以我用它.map來獲取 URL 本身。列印出這個:
[ 'https://google.com/', 'https://www.google.com/' ]
然后你可以得到陣列的第一個元素:
got('http://bitly.com/3eZyxM1').then((res) => {
console.log(res.redirectUrls.maps(url => url.href)[0])
})
這給出了這個:
https://google.com/
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/419841.html
標籤:
上一篇:如何使用Nginx對以斜杠結尾的URL進行301重定向?
下一篇:MongoDB學習筆記:概述
