我在iPhone 5上进行API调用时遇到问题。
我在组件内部进行了以下API调用
import FavouritesService from "../../api/FavouritesService";
const Favourites = () => {
const getFavs = () => {
favouritesService.getFavourites(0, 10, "FULL").then(response => {
if (response.success === false) {
//...
} else {
//...
}
});
};
};
export default Favourites;
获取api端点并在导入中调用函数的FavouritesService
如下所示。
import api from "./api";
class FavouriteService {
getFavourites(page, pageSize, view) {
return api.get(
"/api/social-groups?page=" +
encodeURIComponent(page) +
"&pageSize=" +
encodeURIComponent(pageSize) +
"&view=" +
encodeURIComponent(view) +
"&type=FAVOURITE"
);
}
}
export default FavouriteService;
我在api.js
文件中执行API本身如下...
import _ from "lodash";
import "babel-polyfill";
import "isomorphic-fetch";
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
function handleFetchError(error) {
// Here is where I get TypeError: Type error
if (error) {
return { success: false, error: error };
}
}
function payloadOptions(method, body) {
var postBody = body;
var contentType = "application/x-www-form-urlencoded";
if (typeof postBody === "object") {
postBody = JSON.stringify(postBody);
contentType = "application/json";
}
return {
method: method,
body: postBody,
headers: {
"Content-Type": contentType
}
};
}
const defaultOptions = {
redirect: "error",
headers: {
Accept: "application/json"
}
};
class API {
request(url, options) {
return fetch(url, _.defaultsDeep(options || {}, defaultOptions))
.then(handleErrors)
.then(response => response.json())
.catch(handleFetchError);
}
get(url, options) {
return this.request(
url,
_.defaultsDeep(options || {}, payloadOptions("GET"))
);
}
}
export default new API();
这是handleFetchError
发生错误的地方,error
返回TypeError: Type error
。当我console.log
这个,这就是我得到的,我无法进一步深入实际检查这里发生了什么。
我试图谷歌这个,但没有其他人似乎有这个特定的问题所以我认为我在做这个GET请求的某个步骤出错了。
任何帮助都会非常感激,因为我已经坚持了一段时间。
我发现我必须使用polyfill才能让我获取。
这answer帮助弄清楚我必须安装whatwg-fetch