Jump to content

Recommended Posts

I can't find this documented any where but what responses are available other than json? I have this function:

function requests(url) {
   return fetch(url).catch(function(error) {
      return(null);
   })
   .then(function(response) {
      if (response==null) {
        return(null);
      }
      else if (!response.ok) {
        console.log("caught error: "+response.status);
      }         
       try {
          return response.json();
       } catch(e) {
         return resonse.html();
       }
   });
}

The response can be either json or html. When html results I get an error:

VM13:1 Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

How do I tell the difference since try/catch doesn't work? TIA.

 

Link to comment
https://forums.phpfreaks.com/topic/315216-types-of-fetch-responses/
Share on other sites

3 hours ago, gw1500se said:

what responses are available other than json?

The response data could be anything.  JSON is common so there's a method on the response object to parse it, but you could get whatever data you wanted as either text or binary data.

You should be looking at the Content-type header to find out what the type is and react accordingly.

3 hours ago, gw1500se said:

since try/catch doesn't work?

Because those functions immediately return a promise, which is an action which won't fail.  The failure comes later and the promise is rejected, which you handle with .catch() as described in your other thread.

17 hours ago, requinix said:

Yes, really. Those never showed up in any of my searches. Thanks for the links.

Edited by gw1500se
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.