问题
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.
回答1:
Using unfetch you can do:
const fetch = unfetch.bind();
If you want to use window:
const fetch = window.fetch.bind(window);
回答2:
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',
},
回答3:
Using Axios instead of Fetch solved the problem for me.
来源:https://stackoverflow.com/questions/44720448/fetch-typeerror-failed-to-execute-fetch-on-window-illegal-invocation