Fetch TypeError:无法在"Window"上执行"fetch":非法调用 [英] Fetch TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
本文介绍了Fetch TypeError:无法在"Window"上执行"fetch":非法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用fetch调用来自React的后端,而没有像Axios这样的库.
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);
}
})
我还包括了npm模块,它是polyfill https://www.npmjs.com/package/unfetch 并将其导入我的代码
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] }
我不明白是什么问题.
推荐答案
使用提取功能,您可以执行以下操作:
Using unfetch you can do:
const fetch = unfetch.bind();
如果要使用窗口:
const fetch = window.fetch.bind(window);
这篇关于Fetch TypeError:无法在"Window"上执行"fetch":非法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文