인프런 커뮤니티 질문&답변
급합니다 ㅠㅠ 도와주십쇼 고수님들 리액트네이티브입니다.
작성
·
441
·
수정됨
0
리액트네이티브에서 카카오로 로그인하는건 되는데 카카오로 회원가입하려는게 안됩니다.
카카오 개발자도 해서 테스트용 리다이랙트 유알아이랑 네이티브 앱 발급키도 받았씁니다.
현재 어플을 만들고 있는 중이거든요 프로젝트로 ㅠ
근데 카카오 로그인은 됩니다.
근데 카카오 회원가입화면이 이 밑에 사진ㅊㅓ럼 적용되게 하고 싶은데 잘 안되네요 도와주십시오
뭐가 문제인지
맨첫번쨰 코드는 App.js 코드이고 2번쨰 세번쨰 코드는 2가지로 구현해봣는데 안되는 코드들입니다 ㅠㅠㅠ
import React, { useState } from 'react';
import { StyleSheet, View } from 'react-native';
import KakaoLogin from './component/KakaoLogin';
import Main from './component/Main';
import Sign from './component/Sign';
import KakaoSign from './component/KakaoSignUp';
import Superlogin from './component/Superlogin';
import { name as appName } from './app.json';
import { AppRegistry } from 'react-native';
// 각 페이지 컴포넌트를 렌더링하는 App 컴포넌트
const App = () => {
const [currentPage, setCurrentPage] = useState('Main');
// 현재 페이지에 따라 해당 컴포넌트를 렌더링하는 함수
const renderCurrentPage = () => {
switch (currentPage) {
case 'Main':
return <Main onSignUp={() => setCurrentPage('Sign')} onKakaoLogin={() => setCurrentPage('KakaoLogin')} />;
case 'Sign':
return <Sign onSignUpComplete={() => setCurrentPage('Main')} onKakaoSignUp={() => setCurrentPage('KakaoSignUp')} />;
case 'KakaoLogin':
return <KakaoLogin />;
case 'KakaoSignUp':
return <KakaoSign onSignUpComplete={() => setCurrentPage('Main')} />;
case 'super':
return <Superlogin />;
default:
return <Main onSignUp={() => setCurrentPage('Sign')} onKakaoLogin={() => setCurrentPage('KakaoLogin')} />;
}
};
return <View style={styles.container}>{renderCurrentPage()}</View>;
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
});
// App 컴포넌트를 앱 레지스트리에 등록
AppRegistry.registerComponent(appName, () => App);
export default App;import React, { useEffect, useState } from 'react';
import { Button, Platform } from 'react-native';
import * as AuthSession from 'expo-auth-session';
import * as Random from 'expo-random';
import { StyleSheet } from 'react-native';
const useProxy = Platform.select({ web: false, default: true });
const redirectUri = AuthSession.makeRedirectUri({ useProxy });
export default function App() {
const [request, response, promptAsync] = AuthSession.useAuthRequest(
{
clientId: '',
redirectUri,
responseType: 'code',
scopes: ['profile', 'account_email'],
extraParams: {
response_type: 'code',
},
},
{ useProxy }
);
useEffect(() => {
if (response?.type === 'success') {
const { code } = response.params;
// TODO: 이 코드를 백엔드로 전송하여 액세스 토큰과 리프레시 토큰을 교환하세요.
const fetchAccessToken = async () => {
try {
// 백엔드 엔드포인트에 맞게 URL을 수정해주세요.
const response = await fetch('YOUR_BACKEND_ENDPOINT', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ code }),
});
const data = await response.json();
// 성공적으로 토큰을 받아온 경우
console.log(data); // Or perform other actions based on the received tokens
} catch (error) {
console.error(error);
}
};
fetchAccessToken();
}
}, [response]);
return (
<Button
disabled={!request}
title="카카오 계정으로 회원가입"
onPress={() => {
promptAsync();
}}
/>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 24,
backgroundColor: '#fff',
},
});KakaoSignup.jsimport React, { useEffect } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import * as AuthSession from 'expo-auth-session';
import * as WebBrowser from 'expo-web-browser';
// Make sure you complete the authentication session if the app is opened via a deep link
WebBrowser.maybeCompleteAuthSession();
const KakaoSignUp = () => {
// Replace 'YOUR_KAKAO_REST_API_KEY' with your actual Kakao REST API Key
// For production, replace 'yourapp://redirect' with your actual redirect URI
const [request, response, promptAsync] = AuthSession.useAuthRequest({
clientId: '',
redirectUri: AuthSession.makeRedirectUri({
useProxy: false,
native: ' http://localhost:8082/KakaoSign', // Custom URI scheme for standalone apps
}),
responseType: 'code',
scopes: ['profile', 'account_email'],
extraParams: {
response_type: 'code',
},
}, { useProxy: false });
useEffect(() => {
if (response?.type === 'success') {
const { code } = response.params;
console.log('Authorization Code:', code);
// Send the authorization code to your backend server to exchange it for an access token
// and then proceed with user sign-up or sign-in process
}
}, [response]);
// Render a button that, when pressed, initiates the OAuth flow
return (
<View style={styles.container}>
<Text style={styles.header}>MealJoy 회원가입</Text>
<TouchableOpacity
disabled={!request}
onPress={() => {
promptAsync();
}}
style={styles.button}
>
<Text style={styles.buttonText}>카카오 계정으로 회원가입</Text>
</TouchableOpacity>
</View>
);
};
// Define your styles for the components
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
backgroundColor: '#fff',
},
header: {
fontSize: 22,
fontWeight: 'bold',
marginBottom: 20,
},
button: {
backgroundColor: '#FEE500',
padding: 15,
borderRadius: 10,
marginVertical: 10,
},
buttonText: {
color: '#000',
fontWeight: 'bold',
},
});
export default KakaoSignUp;답변 1
0
안녕하세요, 인프런 AI 인턴입니다. 재희님, 리액트 네이티브 프로젝트에서 카카오 회원가입 구현에 어려움을 겪으시는군요. 제공해주신 코드와 설명을 바탕으로 몇 가지 점검해볼 사항들을 말씀드릴게요.
- 코드 상의
clientId가 비어 있는데, 카카오 개발자 콘솔에 등록한 애플리케이션의REST API Key를 입력해야 합니다.
redirectUri를 애플리케이션 설정과 일치하는 URI로 설정했는지 확인하세요. 웹뷰나 네이티브 앱에서 사용할redirectUri가 올바르게 설정되어 있어야 합니다.
- OAuth 인증 과정에 사용되는 scope이 충분한지, 즉
profile과account_email이외에 회원가입에 필요한 추가적인 정보가 있다면 scope에 포함되어 있는지 확인하세요.
- 토큰을 받아온 후, 해당 토큰으로 서버에 요청을 보내 사용자 정보를 가져오고 회원가입 처리를 하는 로직이 누락되어 있지 않은지 검토하십시오.
useEffect내부에서 토큰을 교환할 때 사용하는 백엔드 엔드포인트 URL이'YOUR_BACKEND_ENDPOINT'으로 되어 있지만, 실제 서버 엔드포인트로 변경되어 있는지 확인하세요.
에러 메시지가 나타나거나 구체적인 실패 사유가 있다면, 그 내용을 함께 공유해주시면 더 구체적으로 어떤 부분이 문제인지 파악하는 데 도움이 될 것입니다.
제공해드린 내용을 바탕으로 코드를 점검해보시고, 만약 문제가 계속되면 인프런 웹사이트의 계정정보 변경 페이지에서 현재 상황을 상세히 설명하여 문의를 해보시는 것도 좋은 방법일 수 있습니다.
프로젝트에 성공하시길 바랍니다.





드디어 답변을 달아주셧군요 ㅠㅠ... 일단 해보고 다시 말씀드리겠습니다!! 감사합니다 ㅠㅠ