프론트엔드 : react
// callback.tsx
import React, { useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import axios from 'axios'
import useTokenStore from '../../components/store/tokenStore'
const Callback = () => {
const navigate = useNavigate()
const location = useLocation()
const { accessToken, setAccessToken } = useTokenStore()
useEffect(() => {
// 서버에 인가코드 전송하는 함수
const sendAuthorizationCodeToServer = async (code: string) => {
try {
const response = await axios.post(
'http://localhost:3000/auth/login/kakao',
{
code,
},
)
// 토큰 스토어에서 받은 토큰 설정
setAccessToken(response.data.accessToken)
console.log(setAccessToken)
navigate('/nickname')
} catch (error) {
console.error(
'서버로 인가 코드를 전송하는 과정에서 오류가 발생:',
error,
)
}
}
// 현재 URL에서 인가코드 파라미터 값 가져오기
const authorizationCode = new URLSearchParams(location.search).get('code')
// 서버에 인가 코드 전송 함수 호출
if (authorizationCode) {
sendAuthorizationCodeToServer(authorizationCode)
console.log('인가 코드:', authorizationCode)
} else {
console.error('인가 코드를 찾을 수 없음')
}
}, [location, navigate, setAccessToken])
return (
<div>
콜백 페이지
<div></div>
</div>
)
}
export default Callback
백엔드 : nest.js
// auth.service.ts
import { Injectable, UnauthorizedException } from '@nestjs/common';
import axios from 'axios';
import * as qs from 'qs';
@Injectable()
export class AuthService {
async kakaoLogin(param: { code: string; domain: string }): Promise<any> {
const { code, domain } = param;
const kakaoKey = '';
const kakaoTokenUrl = 'https://kauth.kakao.com/oauth/token';
const kakaoUserInfoUrl = 'https://kapi.kakao.com/v2/user/me';
const body = {
grant_type: 'authorization_code',
client_id: kakaoKey,
redirect_uri: `${domain}/auth/login/kakao`,
code,
};
const headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
};
try {
const response = await axios({
method: 'POST',
url: kakaoTokenUrl,
timeout: 30000,
headers,
data: qs.stringify(body),
});
if (response.status === 200) {
console.log(`kakaoToken : ${JSON.stringify(response.data)}`);
const headerUserInfo = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Authorization: 'Bearer' + response.data.accessToken,
};
console.log(`url : ${kakaoTokenUrl}`);
console.log(`headers : ${JSON.stringify(headerUserInfo)}`);
const responseUserInfo = await axios({
method: 'GET',
url: kakaoUserInfoUrl,
timeout: 30000,
headers: headerUserInfo,
});
console.log(`responseUserInfo.status : ${responseUserInfo.status}`);
if (responseUserInfo.status === 200) {
console.log(
`kakaoUserInfo : ${JSON.stringify(responseUserInfo.data)}`,
);
return responseUserInfo.data;
} else {
throw new UnauthorizedException();
}
} else {
throw new UnauthorizedException();
}
} catch (e) {
console.log(e);
throw new UnauthorizedException();
}
}
}
어떻게 고쳐야할지 모르겠어서 질문드려요 ㅠㅠ