Search code examples
javascriptwordpressecmascript-6fetches6-promise

Why does fetch return 302 status code but XHR doesn't?


I'm using fetch to query my own WordPress REST API endpoint. However, every request that I make with fetch ends up with a infinite loop of 302 status codes until fetch finally errors with TOO_MANY_REDIRECTS.

illustration of problem

This is on Chrome 56, using the native fetch. But when I visit the endpoint using my browser, use XHR or Postman, I always get 200 as the status.

XHR on the other hand...

XHR doesn't suffer from this problem

Code relevant to this problem:

  static checkStatus(email = null) {
    const cookie = Cookies.get('cookiename');
    const data = email || cookie;

    if (!cookie && !email) {
      return Promise.reject(new Error('No data given.'));
    }

    // This works.
    return new Promise((resolve, reject) => {
      request({
        url: `/wp-json/woo/donate/status/?email=${data}`,
        method: 'GET',
        success: (response) => {
          resolve(response);
        },
        error: (error) => {
          reject(error);
        }
      })
    });

    // This doesn't.
    return fetch(`/wp-json/woo/donate/status/?email=${data}`, {
      method: 'GET',
    });
  }

Please note that I do not actually have two consecutive return statements in my code, that's just for demo. I'm using request() as a wrapper to XHR, you can find the source for that here.

So how do I go around this? I know fetch is still "experimental", but I've used it in several already shipped projects by bundling a polyfill to browsers that don't support it just yet. This is a new thing.


Solution

  • This problem was resolved by "rebuilding" WordPress by destroying my local Vagrant machine, and starting it again.

    For once, turning it on and off again fixed the problem.