Efaz
Efaz

Reputation: 304

Uncaught (in promise) TypeError: response is undefined using Fetch API

I am trying to make a POST request and print the response. My code:

async function create_invite(){
    console.log("creating.....")
    const response = await fetch('https://localhost:8080/webhooks', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload)
    }).catch(error => console.log(error))
    console.log(response.json())
}

document.getElementById('create_invite').addEventListener("click", create_invite)

But I getting this error

Uncaught (in promise) TypeError: response is undefined

I tried adding cors in the header but still doesnt work

Upvotes: 1

Views: 4333

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

Don't mix await with .then and .catch, it's easy to get confused. Your await is applying to the promise from .catch, not the promise from fetch. It looks like the fetch is failing, triggering the catch, which converts rejection into fulfillment with undefined. You'll need to look at why the fetch is failing, but it's still important to update the code.

There are a couple of other issues as well: before calling response.json, be sure to check whether the HTTP operation succeeded (fetch only rejects on network errors, not HTTP errors; an API footgun). Also, your code was trying to console.log the result of response.json directly, which is a promise; instead, await it so you see the data once it's been read and parsed.

Putting that all together:

async function create_invite() {
    console.log("creating.....")
    try {
        const response = await fetch('https://localhost:8080/webhooks', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(payload),
        });
        if (!response.ok) {
            throw new Error(`HTTP error ${response.status}`);
        }
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.log(error);
    }
}

But, I strongly encourage you not to catch errors there unless that's the top-level entry point (an event handler, etc.). Better to let them propagate to the caller (until the top-level entry point).

Upvotes: 3

Related Questions