apollo-link-rest: "Headers is not defined" occur when using apollo-link-rest in weixin mini program

  • has-reproduction

When we try to use apollo-link-rest in weixin mini program, we encounted a problem which has throw an error as below:

 Headers is not defined 
 ReferenceError: Headers is not defined

As I found the source code in RestLink.ts, it does try to find the Headers, but absolutely, there is no Headers under weixin environment, so can anyone help to provide some hack or solutions to solve this issue? Much appreciate if you could help, thanks.

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 2
  • Comments: 28

Most upvoted comments

Here’s what ended up working for me:

import clientFetch from 'unfetch';
import serverFetch, { Headers as ServerHeaders } from 'node-fetch';

const client = typeof document !== 'undefined';
global.Headers = client ? global.Headers : ServerHeaders;
const customFetch = client ? clientFetch : serverFetch;

const acmeLink = new JsonApiLink({
  …
  credentials: 'same-origin',
  customFetch,
});

I was able to fix this issue by using custom fetch

import fetch from "isomorphic-fetch"

const restLink = new RestLink({
  uri: "https://...",
  customFetch: fetch,
  headers: {
    "Content-Type": "application/json",
  },
})

@fbartho Hi! I’m facing this problem on ios 9.3.5.I tried import the fetch-headers polyfill but not work. I found that the header instance from fetch-headers doesn’t have the forEach method(see below). image

Is there any other solutions?

I solved this problem by using the fetch polyfill.

import * as Polyfillheaders from 'fetch-headers'
import fetch from 'isomorphic-unfetch'

// hook in the Headers polyfill for your environment!
global.Headers = global.Headers || Polyfillheaders;

function customFetch(url, options) {
  const headers = options.headers.entries().reduce((accumulator, h) => {
    accumulator[h[0]] = h[1]
    return accumulator
  }, {})
  return fetch(url, { ...options, headers })
}

const restLink = new RestLink({
  uri: CONTENTFUL_CONTENT_DELIVERY_API,
  customFetch,
})

Something like the above might do the trick @2wheelcoder

@VinSpee 's solution worked for me for a Gatsby JS application as well.

Thanks @VinSpee —this was exactly what I needed