1

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

1
  • you must be hitting the .catch which returns undefined Commented Aug 17, 2021 at 11:29

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

5 Comments

in Chrome, nothings gets printed in the console. The very first log "creating....." shows up for a second then disappears.
I changed the code, now Im getting TypeError: NetworkError when attempting to fetch resource.
@Efaz - That's consistent with your original issue, because that would have gone to the catch and been converted to fulfillment with undefined. It's telling you that your browser can't reach https://localhost:8080. So you need to look at why that is. (For instance, is your server really running on port 8080? Is it really doing SSL? Is there an issue with the certificate?)
the server is working fine and the POST request is also working. I can see the change created by the POST request, but for some reason I am not getting the response properly. I tried Postman and made the same request and it worked.
@Efaz - Did you look in the browser console / network tab? Sounds like you're hitting the Same Origin Policy. More here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.