2016-01-06 16 views
10

我正在編寫一個圍繞fetch的包裝,我希望在做出請求之前在URL中添加一些內容,例如識別查詢參數。我無法弄清楚如何使用不同於原始URL的給定Request對象的副本。我的代碼如下所示:如何將請求對象複製到不同的URL?

// My function which tries to modify the URL of the request 
function addLangParameter(request) { 
    const newUrl = request.url + "?lang=" + lang; 
    return new Request(newUrl, /* not sure what to put here */); 
} 

// My fetch wrapper 
function myFetch(input, init) { 
    // Normalize the input into a Request object 
    return Promise.resolve(new Request(input, init)) 
     // Call my modifier function 
     .then(addLangParameter) 
     // Make the actual request 
     .then(request => fetch(request)); 
} 

我試圖把原來的請求作爲第二arguent到Request構造,像這樣:

function addLangParameter(request) { 
    const newUrl = request.url + "?lang=" + lang; 
    return new Request(newUrl, request); 
} 

這似乎是複製最老的請求的屬性,但似乎並未保留舊請求的body。例如,

const request1 = new Request("/", { method: "POST", body: "test" }); 
const request2 = new Request("/new", request1); 
request2.text().then(body => console.log(body)); 

我希望記錄「測試」,但它會記錄空字符串,因爲正文不會被複制過來。

我是否需要做更明確的事情來正確地複製所有的屬性,或者是否有一個很好的捷徑可以爲我做一些合理的事情?

我使用的是github/fetch填充,但已經在最新的Chrome中使用polyfill和原生fetch實現進行了測試。

+0

不顯示僞代碼:顯示真實代碼。 –

+0

@ Mike'Pomax'Kamermans我添加了實際的代碼。我認爲這會讓人難以理解實際問題,也許會有所幫助。 – Xymostech

+0

而不是更難,您的新代碼通過顯示您在代碼本身中使用Request對象,實際上明確了您詢問的內容。 –

回答

7

它看起來像你最好的選擇是使用Body接口的請求實現閱讀正文:

https://fetch.spec.whatwg.org/#body

這隻能異步的,因爲潛在的「消耗體內」操作始終異步讀取和返回一個承諾。像這樣的東西應該工作:

const request = new Request('/old', { method: 'GET' }); 
const bodyP = request.headers.get('Content-Type') ? request.blob() : Promise.resolve(undefined); 
const newRequestP = 
    bodyP.then((body) => 
    new Request('/new', { 
     method: request.method, 
     headers: request.headers, 
     body: body, 
     referrer: request.referrer, 
     referrerPolicy: request.referrerPolicy, 
     mode: request.mode, 
     credentials: request.credentials, 
     cache: request.cache, 
     redirect: request.redirect, 
     integrity: request.integrity, 
    }) 
); 

這樣做後,newRequestP將是解決到您想要的請求的承諾。幸運的是,無論如何,抓取都是異步的,所以你的包裝不應該受到這個嚴重的阻礙。 (請注意:使用.blob()關閉一個沒有body的請求的主體似乎返回一個零長度的Blob對象,但是在GET上指定任何主體,甚至是零長度的對象都是不正確的或HEAD請求,我相信檢查原始請求是否有Content-Type設置是否具有正文的準確代理,這是我們真正需要確定的。)

+2

看起來,這在github/fetch polyfill(它沒有適當地設置'Content-Type'頭文件)中目前沒有工作,但是在Chrome中這很適用。謝謝! – Xymostech

+0

一些很好的信息:https://github.com/whatwg/fetch/issues/191 – Endless

相關問題