我正在編寫一個圍繞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
實現進行了測試。
不顯示僞代碼:顯示真實代碼。 –
@ Mike'Pomax'Kamermans我添加了實際的代碼。我認爲這會讓人難以理解實際問題,也許會有所幫助。 – Xymostech
而不是更難,您的新代碼通過顯示您在代碼本身中使用Request對象,實際上明確了您詢問的內容。 –