我尝试使用 fetch 从 React 调用后端,而无需像 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 模块,它是 polyfillhttps://www.npmjs.com/package/unfetch https://www.npmjs.com/package/unfetch并将其导入我的代码中
import fetch from 'unfetch'
console.log(fetch) returns in console:
function fetch() { [native code] }
我不明白有什么问题。
使用 unfetch 您可以执行以下操作:
const fetch = unfetch.bind();
如果你想使用窗口:
const fetch = window.fetch.bind(window);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)