0

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

Efaz
  • 284
  • 2
  • 12

1 Answers1

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

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • in Chrome, nothings gets printed in the console. The very first log "creating....." shows up for a second then disappears. – Efaz Aug 17 '21 at 12:08
  • I changed the code, now Im getting TypeError: NetworkError when attempting to fetch resource. – Efaz Aug 17 '21 at 12:23
  • @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?) – T.J. Crowder Aug 17 '21 at 13:01
  • 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 Aug 17 '21 at 13:10
  • @Efaz - Did you look in the browser console / network tab? Sounds like you're hitting the Same Origin Policy. [More here](https://stackoverflow.com/questions/20035101/why-does-my-javascript-code-receive-a-no-access-control-allow-origin-header-i). – T.J. Crowder Aug 17 '21 at 13:13