react-refetch icon indicating copy to clipboard operation
react-refetch copied to clipboard

Promise is not rejected upon redirect fail / CORS

Open diegodurli opened this issue 9 years ago • 4 comments

Hi!

Thanks for this library, is awesome!

I've been facing the following error when trying to request an URL (http) that redirects me to another URL (https).

image

Seems that RR is not firing rejected state, since I get an error and its state keeps on pending.

I tried to put redirect: 'error', but it keeps behaving the same way: I get an error and PromiseState continues on pending.

Version: 0.8.0.

This is kind of a report / question, mainly because I'm maybe doing something wrong.

Thank you!

diegodurli avatar Aug 10 '16 00:08 diegodurli

Do you know if the underlying Promise is actually rejected? Also, which fetch lib are you using?

ryanbrainard avatar Aug 10 '16 01:08 ryanbrainard

Hey @ryanbrainard! Thanks for replying!

I'm using a Chrome native fetch implementation, didn't change to add a custom one. Not sure about the underlying Promise being rejected. There's a specific way to check it?

diegodurli avatar Aug 10 '16 18:08 diegodurli

fetch doesn't reject unless the network connection fails. Otherwise the response resolves, and the HTTP status code must be checked in then.

Here's an ES6/ES2015 fetch wrapper to handle unsuccessful responses:

const fetch = require('node-fetch');

function fetchJson(...args) {
  return fetch(...args)
    .then( response => detectStatus(response, args) );
}

function detectStatus(response, originalArgs) {
  const status = response.status;
  if (status >= 200 && status <= 299) {
    return response.json();
  } else {
    if (originalArgs instanceof Array) {
      throw new Error(`${response.status} ${response.statusText} from request to ${originalArgs[0]}`);
    } else {
      throw new Error(`${response.status} ${response.statusText}`);
    }
  }
}

module.exports = {
  fetchJson,
  detectStatus
}

mars avatar Dec 03 '16 03:12 mars

@mars Thanks for the snippet. You can just check response.ok if you want to save some typing.

tkh44 avatar Jan 24 '17 19:01 tkh44