[英]Mock HTTP Requests on the client
我正在使用通過 CDN 提供的 3rd 方 JavaScript API 庫。 該庫公開了在幕后執行我無法控制的 HTTP 請求的方法。 是否可以攔截 HTTP 請求並更改客戶端上的響應。
例如,假設該庫是一個通過 CDN 交付的 JavaScript 數學庫,該庫將變量mathcdn
與一些數學函數(如add
一起公開:
<script src="math.cdn.com"></script>
<script>
var sum = mathcdn.add([4, 4])
</script>
如果在幕后, mathcdn.add
方法向數學 API 發出 HTTP 請求以實際計算兩個數字的總和,我可以告訴請求只是模擬響應嗎?
例如,當庫想要調用api.com/add?nums[4,5]
,實際上並不發送請求,而是模擬{sum: 9}
的響應。
我在用mocks
編寫測試時已經看到了這一點,但我需要在客戶端上這樣做。
據我所知,擴展的webRequest APIs
確實允許您攔截 HTTP 請求。 但我認為你不能用普通的 javascript API 做到這一點,因為它會導致安全問題。
但是,您仍然可以通過一些變通方法實現類似的結果。 例如,首先劫持window.fetch()
。
<script>
// In case you need to use it again.
const originalFetch = window.fetch
window.fetch = function(resource, init) {
// Let some requests act as usual,
// e.g., requests from other 3rd-party libraries.
if (...) return originalFetch(resource, init)
// Extract the information you need,
// e.g., query string in the url,
// and create the corresponding result.
const result = ...
// Wrap the result in a Response object,
// which is how the original fetch returns it.
// So it won't break the library's following code.
return new Response(result)
}
</script>
<script src="math.cdn.com"></script>
XMLHttpRequest
。async
屬性的腳本,因為執行順序將變得不可預測,並且庫可能在你替換它之前存儲對window.fetch()
的引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.