export async function POST(req: NextApiRequest) {
try {
const { url } = await req.json(); // 요청 본문에서 URL 추출
console.log('Fetching content from URL:', url);
// 해당 URL에서 데이터를 가져오기
const response = await axios.get(url); // 외부 API나 웹 페이지에서 데이터 가져오기
return NextResponse.json(response.data, { status: 200 }); // 성공적으로 데이터 반환
} catch (err) {
console.error('Error fetching article content:', err);
return NextResponse.json(
{ message: 'Internal Server Error!' },
{ status: 500 }
); // 에러 응답 반환
}
}
사용할 HTTP
메서드의 용도에 맞게 이름을 설정한다.
위의 예시에서는 POST
형식이라서 함수 형식을 이렇게 설정한 것이다
그리고 바디의 데이터를 가져올 때 req.json
을 통해 값을 가져올 수 있음
그리고 내부에서 다른 HTTP 메서드 호출이 가능한 점이 있다
URL {
href: '<http://localhost:3000/api/news/search?field=%EA%B3%BC%ED%95%99>',
origin: '<http://localhost:3000>',
protocol: 'http:',
username: '',
password: '',
host: 'localhost:3000',
hostname: 'localhost',
port: '3000',
pathname: '/api/news/search',
search: '?field=%EA%B3%BC%ED%95%99',
searchParams: URLSearchParams { 'field' => '과학' },
hash: ''
}
요청의 url을 이용해 URL을 생성하고 searchParams를 이용하여 field 값을 가져와준다.
URLSearchParams { 'field' => '과학' }
...
const field = searchParams.get('field'); // 쿼리 파라미터에서 field 가져오기
export async function POST(req: Request) {
const { code } = await req.json(); // POST 요청의 본문 추출
// 카카오에서 액세스 토큰 요청
try {
const body = {
client_id: process.env.NEXT_PUBLIC_REST_API_KEY,
grant_type: 'authorization_code',
redirect_uri: process.env.NEXT_PUBLIC_REDIRECT_URI,
code,
};
const token = await axios.post(
`${process.env.NEXT_PUBLIC_KAKAO_TOKEN_URI}`,
body,
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
}
);
console.log(token.data);
if (token.status !== 200) {
return NextResponse.json({ message: 'Token Error' }, { status: 404 });
}
const accessToken = token.data.access_token;
// 사용자의 정보 요청
const userResponse = await axios.get(
`${process.env.NEXT_PUBLIC_KAKAO_USER_REQUEST_URI}`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
console.log('사용자 정보 가져오기 성공 ', userResponse.data);
if (userResponse.data) {
return NextResponse.json(userResponse.data, { status: 200 });
} else {
return NextResponse.json({ message: 'Not Found user' }, { status: 404 });
}
} catch (error) {
console.error('Error getting access token or user info:', error);
return NextResponse.json(
{ message: 'Internal Server Error' },
{ status: 500 }
);
}
}
각각 HTTP 요청에 대한 에러 처리를 철저히 해주어야 한다
어디서 에러가 났는지 확인할 수 있어야 수정도 가능하기 때문임