개발_자 2024. 10. 8. 02:57

트러블 슈팅

챔피언 로테이션 페이지(CSR)

로테이션 api와 챔피언 api를 불러와 아이디가 서로 같은 챔피언을 필터링하게끔 해야한다. 

 

	const fetchRotationData = async () => {
		try {
			const rotationData = await getChampionRotation();
			const championsData = await fetchChampions();

			setRotation(rotationData);
			setChampions(championsData);
		} catch (error) {
			console.log(error);
		}
	};

 

챔피언 목록 페이지에서는 잘만 들어오던 championsData가 CORS 문제가 발생했다.

더보기

Access to fetch at 'https://ddragon.leagueoflegends.com/cdn/14.19.1/data/ko_KR/champion.json' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.Understand this error serverApi.ts:17

CORS 문제는 서버가 브라우저의 요청을 허용하지 않아서 발생한다.

 

해결 방법

1. Router Handler

서버에 직접 요청을 보내는 대신, 백엔드 API를 프록시로 설정하여 요청할 수 있다.

// lol-dex/src/app/api/champions/route.ts

export async function GET() {
	const apiKey = process.env.NEXT_PUBLIC_RIOT_API_KEY;

	...
	const version = await getVersion();
	const res = await fetch(
		`https://ddragon.leagueoflegends.com/cdn/${version}/data/ko_KR/champion.json`,
		{
			headers: {
				"X-Roit_Token": apiKey,
			},
		}
	);

	...

	const data = await res.json();
	const champions: Champion[] = Object.values(data.data);
	return NextResponse.json(champions);
}
// lol-dex/src/utils/riotApi.ts

export async function fetchChampions() {
	const response = await fetch("/api/champions");
	const data = await response.json();
	console.log("champions호출됨");
	return data;
}

 

2. Server Action

클라이언트가 요청을 보낼 때 서버에서 처리되고, 그 결과가 클라이언트에게 반환된다.

서버 액션을 사용하면 별도의 API 라우트 없이도 데이터를 서버에서 처리하고 클라이언트로 가져올 수 있다.

// src/utils/serverApi.ts

"use server";

...

export async function fetchChampions() {
	try {
		const version = await getVersion();
		const res = await fetch(
			`https://ddragon.leagueoflegends.com/cdn/${version}/data/ko_KR/champion.json`
		);

		const data = await res.json();
		const champions: Champion[] = Object.values(data.data);

		return champions;
	} catch (error) {
		console.log(error);
	}
}

 

 

해결 완