我正在构建一个使用API的React应用程序,我现在构建的是两个函数,它们都会GET相同的URL,但会更改API终端的第二部分,例如
我最初编写的代码是这样的:
但是这种第二种方法在控制台中给我一个错误,错误信息为:
URL/?search
或URL/?i=123
。但是我希望实现减少冗余代码,因此想要创建一个仅需要相同URL并基于调用更改URL第二部分的函数。
顺便说一下,这种方法给我带来了问题。我最初编写的代码是这样的:
import {API_MOVIE_URL, API_KEY} from "./ApisConst";
export const getMoviesBySearch = async search => {
try {
const url = `${API_MOVIE_URL}?apikey=${API_KEY}&${search}`;
const response = await fetch(url);
const json = await response.json();
return json;
} catch {
return {
success: false,
result: [],
message: "There is an issue to get data from server. Please try again later.",
};
}
};
export const getMoviesInfo = async movieID => {
try {
const url = `${API_MOVIE_URL}?apikey=${API_KEY}&i=${movieID}&plot`;
const response = await fetch(url);
const json = await response.json();
return json;
} catch {
return {
success: false,
result: [],
message: "There is an issue to get data from server. Please try again later.",
};
}
};
我尝试的更改是:
const fetchAPI = async ({type, query}) => {
const queryParams = {
byString: `&${query}`,
byMovieId: `&i=${query}&plot`,
};
const endpoint = `${API_MOVIE_URL}?apikey=${API_KEY}${queryParams[type]}`;
console.log("fetching", endpoint);
return fetch(endpoint)
.then(res => res)
.catch(() => ({
success: false,
result: [],
message: "There is an issue to get data from server. Please try again later.",
}));
};
export const getMoviesBySearch = async search =>
await fetchAPI({type: "byString", query: search});
export const getMoviesInfo = async movieID =>
await fetchAPI({type: "byMovieId", query: movieID});
但是这种第二种方法在控制台中给我一个错误,错误信息为:
Response {type: "cors", url: "https://www.omdbapi.com/?apikey=API_KEY&s=harry+potter&type=movie", redirected: true, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: true
status: 200
statusText: ""
type: "cors"
url: "https://www.omdbapi.com/?apikey=API_KEY&s=harry+potter&type=movie"
第一种方法完美运行,但第二种方法不行,并在尝试寻找解决方案,但无法想到如何使代码更好地优化。
.then(res => res)
而不是.then(res => res.json())
。您在控制台中看到的不是错误,而是响应对象。您随后调用.json()
方法对其进行处理。 - user5734311