Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation

I trying to use fetch for calls to backend from react without libs like Axios.

api.ts

export const sendSuggestion = ((data: any): Promise<any> => {
console.log(JSON.stringify(data));
const apiUrl = `/api/suggest/`;
return fetch(apiUrl, {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify(data)
}).then(checkStatus)
    .then(r => r.json())
    .then(data => {
        console.log(data);
    });
});

const checkStatus = ((response: any) => {
  if (response.ok) {
    return response;
  } else {
    var error = new Error(response.statusText);
    console.log(error);
  //return Promise.reject(error);
  }
})

Also i include npm module which is polyfill https://www.npmjs.com/package/unfetch and import it in my code

 import fetch from 'unfetch'


 console.log(fetch) returns in console:
 function fetch() { [native code] } 

I can`t understand what the problem.

like image 548
Valeriy Donika Avatar asked Jun 23 '17 11:06

Valeriy Donika


3 Answers

Using unfetch you can do:

const fetch = unfetch.bind();

If you want to use window:

const fetch = window.fetch.bind(window);

like image 84
Tiago Gouvêa Avatar answered Oct 26 '22 08:10

Tiago Gouvêa


Very specific use-case, but I encountered this while building a Chrome Extension.

The problem was that I specified headers in the request options as a list of objects, when it should be an object.

I was building the following request:

const requestOptions = {
  method: 'POST',
  searchParams: {
    code: code,
  },
  headers: [
    {'content-type': 'application/x-www-form-urlencoded'},
  ],
};
const getAccessToken = `https://example.com/oauth2/token`;
fetch(getAccessToken, requestOptions)
  .then(r => r.text())
  .then(token => {
    console.log('token is', token);
  });

I fixed it by changing:

headers: [
  {'content-type': 'application/x-www-form-urlencoded'},
],

to:

headers: {
  'content-type': 'application/x-www-form-urlencoded',
},
like image 40
Brad Johnson Avatar answered Oct 26 '22 08:10

Brad Johnson


In my case I had a class like this:

export class HTTPClient {
  constructor(fetch: FetchFunction = window.fetch) {
    this.fetch = fetch;
  }
  
  async performRequest(data: any) {
    return await this.fetch(data);
  }
};

and performRequest throws this error (Fetch TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation).

I've changed it to:

export class HTTPClient {
  constructor(
    fetch: FetchFunction = (...args) => window.fetch(...args)
  ) {
    this.fetch = fetch;
  }

  async performRequest(data: any) {
    return await this.fetch(data);
  }
};

and it works now.

I guess the problem is that in the first example this param was rebound to HTTPClient therefore fetch function had no this referencing window as it needed.

like image 1
Qback Avatar answered Oct 26 '22 10:10

Qback