【问题标题】:Fetch TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation获取类型错误:无法在“窗口”上执行“获取”:非法调用
【发布时间】:2017-06-23 11:32:51
【问题描述】:

我试图在没有像 Axios 这样的库的情况下使用 fetch 来调用后端。

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);
  }
})

我还包括 npm 模块,它是 polyfill https://www.npmjs.com/package/unfetch 并将其导入我的代码中

 import fetch from 'unfetch'


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

我不明白是什么问题。

【问题讨论】:

    标签: javascript node.js fetch


    【解决方案1】:

    使用 unfetch 你可以做到:

    const fetch = unfetch.bind();

    如果你想使用窗口:

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

    【讨论】:

      【解决方案2】:

      非常具体的用例,但我在构建 Chrome 扩展程序时遇到了这个问题。

      问题是我在请求选项中将headers 指定为对象列表,而它应该是一个对象。

      我正在构建以下请求:

      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);
        });
      

      我通过更改来修复它:

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

      到:

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

      【讨论】:

        【解决方案3】:

        使用 Axios 而不是 Fetch 为我解决了这个问题。

        【讨论】:

        • Axios 使用 XHRHttpRequest 而 Fetch 是一个新的 Web API。 Axios 将为您的应用程序添加约 14kb。
        猜你喜欢
        • 1970-01-01
        • 2021-04-26
        • 2021-01-18
        • 1970-01-01
        • 2018-08-13
        • 2019-10-13
        • 1970-01-01
        • 2020-11-19
        • 1970-01-01
        相关资源
        最近更新 更多