배움 __IL/TIL 1기

TIL : 103번째- 230504 [5-1-목]

Mo_bi!e 2023. 5. 4. 18:10

I. 로그인 구현하기

1.  프론트

(1) loginHandler

1) loginHandler 

<script setup>
import { reactive } from 'vue';

let userDtails = reactive({
  username : "",
  password : "",
  role : "",
});

async function loginHandler() {
  console.log(userDtails.username);
  let response = await fetch("http://localhost:8080/members/login", {
    method : "POST",
    headers : {
      "Accept" : "application/json",
      "content-type":"application/x-www-form-urlencoded"
    },
    body:`username=${userDtails.username}&password=${userDtails.password}`
  });
  let json = response.json();
  console.log(json);
}


</script>

<template>
       <!-- 메인 -->
    <main>
      <div class="sign-in">
        <div class="sign-in-logo">
          <img src="/image/logo-black.svg" alt="Rland" />
        </div>
        <form class="sign-in-form">
          <div class="sign-in-form-input">
            <div>
              <input
                type="text"
                class="input-bottom-line"
                placeholder="아이디"
                required
                v-model="userDtails.username"
              />
            </div>
            <div>
              <input
                type="password"
                class="input-bottom-line"
                placeholder="비밀번호"
                required
                v-model="userDtails.password"
              />
            </div>
          </div>

          <div class="sign-in-form-button">
            <div class="wd-100">
              <input type="submit" value="로그인" class="btn btn-default" @click="loginHandler"/>
            </div>
            <div class="font-14">또는</div>
            <div class="wd-100">
              <a href="" class="deco icon-logo-google btn btn-outline"
                >구글로 로그인</a
              >
            </div>
          </div>
        </form>
        <div class="sign-in-find-user font-14">
          <a href="./sign-up.html">회원가입</a> |
          <a href="">비밀번호 찾기</a>
        </div>
      </div>
    </main>

</template>

<style scoped>
    @import url("/css/sign-in.css");

</style>

2way binding을 하는 v-model 을 했다

그리고 클릭이벤트 관련 핸들링을 세팅했다.

 

2) fetch API

async function loginHandler() {
  console.log(userDtails.username);
  let response = await fetch("http://localhost:8080/members/login", {
    method : "POST",
    headers : {
      "Accept" : "application/json",
      "content-type":"application/x-www-form-urlencoded"
    },
    body:`username=${userDtails.username}&password=${userDtails.password}`
  });
  let json = await response.json();
  console.log(json);
}

여기서 headers 요청헤더에 포함될 내용을 정의하는 것이다.

여기서 헤더란 서버에 요청할 때 요청의 추가정보를 의미한다.

 

- Accept 는 특정형식(JSON)형식의 응답을 기대하고 있음을 의미힌다

- content-type 은 요청본문(body)의 데이터가 URL로 인코딩된 폼을 의미한다

이 경우 형식은 key-value 형식을 의미한다

 

이 경우 json()비동기방식으로 처리하기 위해서 await 사용해서 기다린다.

 

3) CORS 세팅

CORS : 다른곳에서 요청하는경우에 이를 위한 해결을 해보자

 

package kr.co.rland.rlandapiboot3.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.pattern.PathPattern;

@Configuration
public class CORSConfig {
    
    @Bean
    WebMvcConfigurer webMvcConfigurer(){
        WebMvcConfigurer configurer = new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("*");
            }
        };

        return configurer;
    }

}

스프링 서버에게 비트의 요청이 온 경우 허락해주는 경우를 의미한다

 

4) API 쿼리문 보기

한편

logging.level.org.hibernate.SQL=DEBUG
spring.jpa.properties.hibernate.format_sql=true

이거 두개를 넣어주면 콘솔에다가 JPA로 만들어진 쿼리문이 출력된다.

(2) UserDetail.js [전액객체 이용]

1) 들어가며

backurl 사이가 완전 분리지만, front별개가 아니야

범용적으로 JS의 모듈을 이용하는 전역변수, 리액티브한 전역변수가 필요하다면 리액티브한 전역변수를 위해서 피니아 라는것을 쓴다.

 

2) 전역객체 만들기

전역객체를 만들어서 얘를 가지고 활용하자

 

<UserDetail.js>

export default{ //null 이 아닌 빈값으로 넣어주자
    username : "newlec", 
    password : "111",
    role : ""

}

<Login.vue>

<script setup>
import { reactive } from 'vue';
import userDetails from '../store/UserDetails';

let user = reactive({
  username : "",
  password : "",
  role : "",
});

async function loginHandler() {
  console.log(user.username);
  let response = await fetch("http://localhost:8080/members/login", {
    method : "POST",
    headers : {
      "Accept" : "application/json",
      "content-type":"application/x-www-form-urlencoded"
    },
    body:`username=${user.username}&password=${user.password}`
  });
  let json = await response.json();
  console.log(json.result.email);

  console.log(json);
  userDetails.username = json.result.userName;
  userDetails.password = json.result.pwd;
  userDetails.email = json.result.email;

  console.log(userDetails);

}


</script>

json 객체전역객체에 담긴 것 각자 살펴볼 수있어

 

3) 결과

SPA새로고침 했을 때 reload가 안되어야해

전역객체로 끌고가도 안날라가게 해야해

이렇게 로그인한 이메일을 볼 수있어! 즉 인증이 성공됐다는 의미야

 

 

4) 로그인, 로그아웃 상황에 따라 다르게 화면에 바인딩하기

 

v-ifv-show 의 공통점은 조건부로 DOM 을 표시하거나 숨기는데 이용되는 것이다.

 

if는 docu 객체가 아예없고, v-show 는 있는거야

즉 렌더링 여부가 다른거야

v-show는 렌더링 되어있지만 display 속성을 조작하여서 숨기는 것이고 -> 자주 토글이 되면 v-show

v-if는 조건부로 렌더링을 하는거야 -> 토글 횟수가 적은경우에! 

 

메모리 사용량에 따라 선택하자

  <li>
    <router-link v-if="userDetails.username != '' "
      to="/login"
      class="icon icon-sign-on"
      title="로그인">
    </router-link>
    <router-link v-if="userDetails.username == '' "
      to="/logout"
      class="icon icon-sign-out"
      title="로그아웃">
    </router-link>
  </li>

조건문으로 있고없고를 만들 수 있다

login logout 두개다 아이콘이 있어야 하는데 하나만 나오게 되었다

 

 

5)

피니아 그전에는 안썻음

 

 


1. 보충

 

 

 

 

2. 회고 

1) 이제 비슷한것을 계속배우고 있다. 어느정도 배우는게 마무리 되고있는것이 느껴진다.

'배움 __IL > TIL 1기' 카테고리의 다른 글

TIL 1기를 끝내며...  (0) 2023.06.15
TIL : 104번째- 230508 [5-2-월]  (0) 2023.05.08
TIL : 102번째- 230503 [5-1-수]  (0) 2023.05.03
TIL : 101번째- 230501 [5-1-월]  (0) 2023.05.01
TIL : 100번째- 230428 [4-4-금]  (0) 2023.04.28