【发布时间】:2019-09-08 22:18:15
【问题描述】:
我在 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;
我的FavouritesService 获取api端点并在导入中调用函数如下。
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 的 api.js 文件如下...
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 请求时的某个步骤出错了。
任何帮助将不胜感激,因为我已经坚持了一段时间。
【问题讨论】:
标签: javascript reactjs fetch