connecting dots

Beginner 13회차 (8/19) | this 키워드, Serverless function, fetch와 axios, 환경변수 설정(.env), Empty Commit, Vercel에 배포 실습, git merge 3가지 종류 본문

Live Class/Beginner

Beginner 13회차 (8/19) | this 키워드, Serverless function, fetch와 axios, 환경변수 설정(.env), Empty Commit, Vercel에 배포 실습, git merge 3가지 종류

dearsuhyun 2024. 8. 20. 15:10

자바스크립트에서의 this 키워드

일반함수: 호출 위치에서 this가 정의됨
화살표 함수: 선언 위치에서 this가 정의됨

일반함수

 

Function.prototype.call()

--> call() 메소드는 주어진 this 값 및 각각 전달된 인수와 함께 함수를 호출합니다.

 

화살표 함수

this를 가지고 있는 함수를 감싸는 함수가 있는지 봐야 함 !

 

 

 

(1) 방법은 보안에 취약

(2) 방법을 통해 안전성을 높여야 함 !

우리 프로젝트에서는 Vercel의 Serverless Functions를 사용해서 api 구현

todos.ts --> https:localhost/api/todos

 

엔드포인트 = {updatedtodo.id}

https://asia-northeast3-heropy-api.cloudfunctions.net/api/todos/${updatedTodo.id}

 

API 코드

서버리스 함수는 한 페이지 당 하나의 함수만 export할 수 있음

기존 코드

 

수정 코드

서버와 api 통신을 위한 범용 코드

 

- req.body

// updatedTodo의 body에 담은 데이터가 req.body로 전달됨

,
body: JDPN.stringify({
  title: updatedTodo.title,
  done: updatedTodo.done
})

 

- 서버리스 코드와 실제 서버가 통신할 때는 method를 채워주면 됨 (프론트쪽과 서버리스코드는 POST로만 통신)

 

환경변수(Environment Variables)

.env 파일에 넣고 .gitignore에 올려서 깃허브에 올라가지 않도록 ! (보안상 중요)

이 파일을 가지고 있는 환경에서만 동작 --> 다른 컴퓨터로 가져갔을 경우 .env 파일 다시 만들어야 함 (따로 관리)

.env 파일

 

가져와서 사용할 때 !
request header에 민감한 정보가 노출되지 않는 것을 볼 수 있음

 

fetch VS axios

// updatedTodo
// fetch
await fetch(
          `https://asia-northeast3-heropy-api.cloudfunctions.net/api/todos/${updatedTodo.id}`,
          {
            method: 'PUT',
            headers: {
              'content-type': 'application/json',
              apikey: 'KDT9_AHMq2s7n',
              username: 'FE1_ParkSuHyun'
            },
            body: JSON.stringify({
              title: updatedTodo.title,
              done: updatedTodo.done
              })
          }
        )

// axios
await axios.post('/api/todos', {
    endpoint: updatedTodo.id,
    method: 'PUT',
    data: {
      title: updatedTodo.title,
      done: updatedTodo.done
    }
  })
// deletedtodo
// fetch
await fetch(
          `https://asia-northeast3-heropy-api.cloudfunctions.net/api/todos/${deletedTodo.id}`, //:todoId
          {
            method: 'DELETE',
            headers: {
              'content-type': 'application/json',
              apikey: 'KDT9_AHMq2s7n',
              username: 'FE1_ParkSuHyun'
            }
          }
        )
        
// axios
await axios.post('/api/todos', {
  endpoint: deletedTodo.id,
  method: 'DELETE',
})

 

 

JSON.stringify /  JSON.parse

fetch의 경우 JSON.stringify로 데이터 전달하면 JSON.parse로 분석하는 과정이 필요

axios는 이 과정이 필요 없음 !

또 fetch는 어떤 method인지 명시해줘야 하는데 axios는 .___ 로 바로 표시 가능

// getTodos

async function getTodos() {
  try {
    const res = await fetch('/api/todos', {
      method: 'POST'
      })
      const data = await res.json()
      console.log('응답 결과', data)
      set({
        todos:data
      })
      
// axios
async function getTodos() {
  try {
    // 객체구조분해할당
    const { data } = await axios.post('/api/todos')
      console.log('응답 결과', data)
      set({
        todos:data
      })

 

 

store 전체 코드

TodoCreator.tsx

수정사항 없을 때 commit 하는 법 (Empty Commit)

git commit --amend
git push origin main -f

 

git merge 병합 옵션

1. Create a merge commit(기본값)

출처(sourse) 브랜치의 모든 커밋이 대상(Target) 브랜치에 병합되는 기본 옵션

a, b, c 커밋 --> 이를 병합하는 하나의 새로운 커밋(M)이 대상 브랜치에 추가 및 연결됨

병합 이력이 남기 때문에 추후 확인할 때 유용

출처: https://www.heropy.dev/p/6hdJi6

 

2. Squash and merge

출처 브랜치의 모든 커밋을 하나로 압축(Squash)해서 대상 브랜치에 한 번에 추가하는 방법

출처 브랜치에 3개의 커밋이 있어도, 대상 브랜치에는 하나의 병합 커밋(M)만 추가됨

중요하지 않은 작은 커밋들을 깔끔하게 정리 가능하지만 추후 이력을 정확하게 확인하기 어렵기 때문에 주의해서 사용

출처: https://www.heropy.dev/p/6hdJi6

 

3. Rebase and merge

출처 브랜치의 모든 커밋을 그대로 대상 브랜치에 추가하는 옵션

병합 커밋(M)을 생성하지 않고 커밋을 쌓는 방법이라 직관적이지만, 여러 브랜치들을 병합할 때 복잡한 충돌 발생 가능

출처: https://www.heropy.dev/p/6hdJi6

 

Vercel 배포

connect Git Repository

 

연결 완료

 

핵심 브랜치 설정(바꿀 수 있음)

 

환경변수 지정

 

지속적인 배포

 

visit 누르면 배포된 내 사이트로 이동 !

 

호출 지역 설정

서울로 설정해야 동작할 때 속도가 빠르게 됨 (기본-워싱턴으로 되어 있음)

 

오류발생 시 확인 (log tab)


* window.alert(123) = alert(123) --> window 객체는 생략 가능함

* fetch와 axios의 차이점이 뭔지 알아야 함 (네트워크 통신은 프론트엔드에서 필수적)

* PR할 때 설명 상세하게 적어주기

* git merge할 때 3가지 병합 옵션 알아두기 (Create a merge commit, Squash and merge, Rebase and merge)

 

https://youtu.be/bdPug9IWz-g?si=EnVhT437U5dVPI18

https://www.heropy.dev/p/QOWqjV

 

데이터 통신을 위한, Fetch 함수와 Axios 라이브러리

서버와 클라이언트 간의 데이터 통신은 웹 개발의 핵심 개념 중 하나로, 자바스크립트에서의 데이터 통신을 위한 fetch 함수와 axios 라이브러리의 사용법을 알아봅니다.

www.heropy.dev

https://www.heropy.dev/p/6hdJi6

 

사례로 이해하는 GitHub Flow

GitHub Flow는 GitHub을 활용하는 브랜치 전략으로, 브랜치를 어떻게 생성하고 병합하는지에 대한 개념입니다. GitHub Flow의 간단한 사용 사례를 통해 브랜치 전략을 이해해 봅시다.

www.heropy.dev

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Function/call

 

Function.prototype.call() - JavaScript | MDN

call() 메소드는 주어진 this 값 및 각각 전달된 인수와 함께 함수를 호출합니다.

developer.mozilla.org

 

 

반응형