我试图使用fetch进行来自反应的后端调用,而没有像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);
}
})
Run Code Online (Sandbox Code Playgroud)
我也包括npm模块,它是polyfill https://www.npmjs.com/package/unfetch并将其导入我的代码中
import fetch from 'unfetch'
console.log(fetch) returns in console:
function fetch() { [native code] }
Run Code Online (Sandbox Code Playgroud)
我不明白是什么问题。