Search code examples
javascriptfetch

Get Fetch Request


I might be overlooking the obvious but is there a way to get the fetch request? (not the response).

A normal fetch looks like something this:

fetch(url, {
                method: method,
                headers: new Headers({
                    'Authorization': token,
                    'Content-Type': 'application/json'
                }),
                body: payload
            })
            .then((response) => response.json())
            .then((responseData) => {
                
                console.log(responseData);
            })

I want the ability to get the method, headers, body, and are data that are passed to fetch in a variable that can be passed around to other methods like a log.


Solution

  • You can't get the request information from a Response object (the thing the promise from fetch is fulfilled with), but you can build a Request object yourself, pass it around, and then use that with fetch. The Request constructor accepts the same parameters fetch does, but instead of doing the operation, it just returns the Request object for it.

    For instance, here's your code done that way:

    // Building the request, which you can then pass around
    const request = new Request(url, {
        method: method,
        headers: new Headers({
            "Authorization": token,
            "Content-Type": "application/json"
        }),
        body: payload
    });
    
    // Using it
    fetch(request)
    .then((response) => {
        if (!response.ok) { // Don't forget this part!
            throw new Error(`HTTP error ${response.status}`);
        }
        return response.json();
    })
    .then((responseData) => {
        console.log(responseData);
    });
    

    (Aside: Note the slight addition to the first fulfillment handler above, to handle the fetch API footgun. fetch doesn't reject its promise on HTTP errors, only network errors; you have to check for HTTP errors yourself. More in my blog post here.)