I am using Cloudflare worker which is triggered by HTTP requests. I want to take the ining request, change the url but leave all other properties untouched, and then issue the request. The structure is loke the following:
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
#change the value of request.url and then...
return fetch(request)
.then(response => {
return response;
});
}
I am using Cloudflare worker which is triggered by HTTP requests. I want to take the ining request, change the url but leave all other properties untouched, and then issue the request. The structure is loke the following:
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
#change the value of request.url and then...
return fetch(request)
.then(response => {
return response;
});
}
Share
Improve this question
asked May 31, 2020 at 15:34
dovod74538dovod74538
1433 silver badges9 bronze badges
3 Answers
Reset to default 5To clone a Request object, but change the URL, you can do this:
new Request("https://example./the/new/url", originalRequest);
Try it in your browser console:
let originalRequest = new Request("https://example.")
let newRequest = new Request("https://voxviva.app", originalRequest);
Inspect newRequest
. You will not see the old URL anywhere.
In my case, I needed to monkey-patch window.fetch
for both options - url as string and also Request object.
This answer https://stackoverflow./a/34641566/3249097 covers how you can change url in the Request
object by duplicating the existing Request
object.
I myself implemented a solution where the Request
is actually changed into simple window.fetch
with url & options.
(function (window) {
const original = window.fetch;
window.fetch = async function () {
let [url, config] = arguments;
if (typeof url === 'string') {
const newUrl = customChangeUrl(url);
return original.apply(window, [newUrl, config]);
}
if (typeof url === 'object') {
const request = url;
const blob = await request.blob();
const body = blob.size > 0 ? blob : undefined;
config = {
body,
cache: request.cache,
credentials: request.credentials,
headers: request.headers,
integrity: request.integrity,
keepalive: request.keepalive,
method: request.method,
mode: request.mode,
redirect: request.redirect,
referrer: request.referrer,
referrerPolicy: request.referrerPolicy,
signal: request.signal,
}
const newUrl = customChangeUrl(request.url);
return original.apply(window, [newUrl, config]);
}
};
})(window);
You can do this:
async function handleRequest(request) {
#change the value of request.url and then...
return fetch({...request, url: "someUrl"})
.then(response => {
return response;
});
}
This will overwrite the url with "someUrl" Hope this helps :)