9. Spring boot + React Native + MongoDB - 로그인, 로그아웃 구현

2024. 6. 17. 00:02·개발일기/Project
목차
  1. frontend
  2. backend
728x90
반응형

자, 이제 로그인을 해보자

frontend

Login.js

import React, {useEffect, useState} from "react";
import {StyleSheet, Text, View, TextInput, Image, Button} from 'react-native';
import axios from "axios";


function Login({navigation}) {
    const [userId, onChangeUserId] = React.useState('');
    const [pw, onChangePw] = React.useState('');

    const baseUrl = "http://localhost:8080/";

    const handleKeyPress = e => { //비밀번호를 입력한 뒤 엔터키 누르면 로그인 진행
        if (e.key === 'Enter') {
            onPressLogin()
        }
    }
    
    const onPressLogin = () => {
        axios.post(baseUrl + "login", {
            userId: userId,
            pw: pw
        })
            .then((res) => {
                console.log("data : ", res.data)
                console.log("data : ", res.data.userId)
                if (res.data.userId === userId) {
                    navigation.navigate('Main', {
                        userId: userId,
                        pw: pw,
                    })
                } else {
                	alert("로그인 정보를 다시 확인해주세요.")
                }
            })
            .catch((err) => console.log(err))
    }

    return (
        <View style={styles.container}>
            <ul>
                {data}
            </ul>
            <Image
                source={{uri: "https://search.pstatic.net/common/?src=http%3A%2F%2Fblogfiles.naver.net%2FMjAyMzEyMzBfMTA1%2FMDAxNzAzOTM0MDE4MTY5.EnQ_Al65sMhrNYFcEunuOIcZD7d_xpXnDhFYsl5k5aog.eHUbc0WA3A0QM0oVp3qLNpNXdDvXYR5I9WKOzDGjrnQg.JPEG.pooh_sk1012%2F%25B9%25D9%25C5%25C1%25C8%25AD%25B8%25E9_%25C0%25CC%25B7%25B9%25B5%25F0%25C0%25DA%25C0%25CE_%25B4%25DE%25B7%25C2_2560x1600.jpg&type=a340"}}
                style={{width: 600, height: 300, borderRadius: 30}}
            />
            <Text style={styles.title}> Calendar </Text>
            <TextInput
                placeholder='Id'
                style={styles.input}
                onChangeText={onChangeUserId}
            />
            <TextInput
                placeholder='Password'
                style={styles.input}
                onChangeText={onChangePw}
                secureTextEntry={true}
                keyboardType="numeric"
                onKeyPress={handleKeyPress}
            />
            <View style={styles.button}>
                <Button
                    color={'#e2d2c1'}
                    textStyle={{textAlign: 'center', font: 40}}
                    title={`Login`}
                    onPress={onPressLogin}
                />
            </View>
            <View style={styles.button}>
                <Button
                    color={'#e2d2c1'}
                    textStyle={{textAlign: 'center', font: 40}}
                    title={`회원가입`}
                    onPress={() => navigation.navigate('Join')}
                />
            </View>
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
    },
    title: {
        fontSize: 30,
    },
    input: {
        height: 40,
        margin: 12,
        borderWidth: 1,
        padding: 10,
    },
    button: {
        width: 170,
        height: 40,
        margin: 12,
        padding: 10,
    }
});

export default Login;

 

backend

LoginRequest.java 파일을 model/Request 폴더에 생성해주었다.

package com.calender.calenderproject_backend.model.Request;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class LoginRequest {
    String userId;
    String pw;
}

 

MemberRepository

package com.calender.calenderproject_backend.repository;

import com.calender.calenderproject_backend.model.Member;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface MemberRepository extends MongoRepository<Member, String> {
	...
    
    Member findMemberByUserIdAndPw(String userId, String pw);
}

 

MemberService

...
    public Member login(String userId, String pw){
        return memberRepository.findMemberByUserIdAndPw(userId, pw);
    }
...

 

 

MemberController

....
    @PostMapping("/login")
    public ResponseEntity<?> memberLogin(@RequestBody LoginRequest request){
        System.out.println("User login: " + request.getUserId());
        return ResponseEntity.ok(memberService.login(request.getUserId(), request.getPw()));
    }
.....

 

 

이제 세션 유지와 로그아웃을 추가해야하는데... 

큰일났다...

컴퓨터가 너무 오래된 아이라.... 자꾸 멈춘다... 앞으로 어떡하지...?

 

 

 

 

 

 

 

 

* 몽고 디비 쿼리 참고

https://steemit.com/kr-dev/@kormanocorp/spring-boot-mongodb-query

728x90
반응형

'개발일기 > Project' 카테고리의 다른 글

8. Spring boot + React Native + MongoDB - 회원 가입 구현  (0) 2024.05.31
7. React Native expo 달력 띄우기  (0) 2024.05.29
6. Spring boot + React Native 연결하기  (0) 2024.05.29
5. Spring boot + MongoDB 연결하기  (0) 2024.04.29
4. Mongo DB 생성  (0) 2024.04.22
  1. frontend
  2. backend
'개발일기/Project' 카테고리의 다른 글
  • 8. Spring boot + React Native + MongoDB - 회원 가입 구현
  • 7. React Native expo 달력 띄우기
  • 6. Spring boot + React Native 연결하기
  • 5. Spring boot + MongoDB 연결하기
길동이이이잉
길동이이이잉
길동이이이잉
코딩 일기
길동이이이잉
코딩 일기일까......?
삽질...... 일기일까?
반응형
250x250
  • 모든 글 (97)
    • 개발일기 (9)
      • Project (9)
      • React (1)
      • DB, SQL (7)
      • Spring (5)
      • AWS (1)
    • 코딩 테스트 (63)
      • 1. String(문자열) (12)
      • 2. Array(1, 2차원 배열) (12)
      • 3. Tow pointers, Sliding wi.. (6)
      • 4. HashMap, HashSet, TreeSe.. (5)
      • 5. Stack, Queue (8)
      • 6. Sorting and Searching (8)
      • 7. Recursive, Tree, Graph (11)
      • 8. DFS, BFS 활용 (0)
      • 9. ... (1)
    • 갔다왔다 워홀! (2)

인기 글

태그

달력프로젝트
Tactical Design
아일랜드
유럽워홀
Oracle
아일랜드워홀
유럽
React
aws업로드
Strategic Design
전술적 설계
워킹홀리데이
s3대용량파일업로드
reactnative
SpringBoot
spring
전략적 설계
s3대용량업로드
AWS
워홀

최근 글

hELLO· Designed By정상우.v4.5.3
길동이이이잉
9. Spring boot + React Native + MongoDB - 로그인, 로그아웃 구현

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.