Javascript 获取类型错误:未能执行';获取';在';窗口';:非法调用
我试图在没有像Axios这样的LIB的情况下使用fetch从react调用后端 api.tsJavascript 获取类型错误:未能执行';获取';在';窗口';:非法调用,javascript,node.js,fetch,Javascript,Node.js,Fetch,我试图在没有像Axios这样的LIB的情况下使用fetch从react调用后端 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
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);
}
})
我不明白问题出在哪里。使用unfetch可以执行以下操作:
const fetch=unfetch.bind()代码>
如果要使用Windows,请执行以下操作:
const fetch=window.fetch.bind(window)代码>非常具体的用例,但我在构建Chrome扩展时遇到了这个问题
问题是,我在请求选项中将标题指定为对象列表,而它应该是对象。
我正在生成以下请求:
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'},
],
致:
使用Axios而不是Fetch为我解决了这个问题。Axios使用了xhrhtprequest,而Fetch是一个新的Web API。Axios将为您的应用程序添加约14kb。
headers: [
{'content-type': 'application/x-www-form-urlencoded'},
],
headers: {
'content-type': 'application/x-www-form-urlencoded',
},