MDN says you can pass in a request to new Request()
to make a copy of it::
A Request object, effectively creating a copy
However that is not the behavior I see when testing, here I am trying to “clone with a modified body” the request
object, which is an intercepted request from a service worker fetch:
request.method
'POST'
x = new Request(request)
Request {method: 'GET', url: 'http://127.0.0.1:8000/[object%20Object]', headers: Headers, destination: '', referrer: 'about:client', …}
x.method
'GET'
As you can see the .method
is not copied (was POST now GET). This makes me wonder how much is actually “cloned”? I could force the method
property, but then what else needs to be forced? It tell me I don’t understand how it works.
Heres my code that doesnt work because of the above behavior
export async function updateCSRFTokenInPOSTRequestBody(csrfToken, request) {
// When performing a sync, the user may have logged out/logged in again, and hence fail csrf check
const body = request.body.replace(/(?<=csrfmiddlewaretoken=)w+(?=&)/, csrfToken);
const init = {
body: body,
};
const newRequest = new Request(request, init);
return newRequest;
}
The error it gives is (which is understandable because of the above behavior):
VM18:1 Uncaught TypeError: Failed to construct 'Request': Request with GET/HEAD method cannot have body.