Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the URL of a Request object from the Fetch API

Say if I have small function that takes a Request object as an argument, and calls the fetch() API.

Except I always want to append something to the url, such as ?foo=bar. I'm curious what the best way would be to go about that.

Example:

function fetchFoo(request) {

   request.url += '?foo=bar';
   return fetch(request);

}

The issue I have is that this won't work. The Fetch API specification states that the url property read-only.

Is there a way to work around this? I'm thinking I might need to construct an all-new Request object, but I'm unsure what a clever way is to inherit all the options from the previous Request object.

Note that I am able to override any other property by using this syntax:

var originalRequest = new Request('/url');
var overriddenRequest = new Request(originalRequest, { method: 'POST' });

Although it wasn't clear from the docs, it seems that the second init parameter takes precedence over the values passed via the originalRequest parameter. I just can't seem to come up with a way to do this for the url as well.

like image 269
Evert Avatar asked Oct 17 '25 19:10

Evert


1 Answers

You could leverage the keys that are on the Request.prototype to build a new Request object in just a few lines.

function newRequest(input, init) {
    var url = input;
    if (input instanceof Request) {
        url = mutateUrl(input.url);

        init = init || {};
        Object.keys(Request.prototype).forEach(function (value) {
            init[value] = input[value];
        });
        delete init.url;

        return input.blob().then(function (blob) {
            if (input.method.toUpperCase() !== 'HEAD' && input.method.toUpperCase() !== 'GET' && blob.size > 0) {
                init.body = blob;
            }

            return new Request(url, init);
        })
    } else {
        url = mutateUrl(url);
    }

    return new Request(url, init);
}

Note the special case for body discussed in this answer.

like image 90
cjbarth Avatar answered Oct 20 '25 08:10

cjbarth