혼자 고민해보기_ 개발/TIL (Today I Learned)

20230809(수)_ 트렐로 프로젝트 진행

nuri-story 2023. 8. 9. 22:36

금일 달성 항목

1) main, card, login, signup 프론트 구현

2) login 프론트 백엔드 연결
3) 팀원 CRUD 리펙토링


문제 해결 과정 1 - 프론트 연결

[문제]

ejs로 프론트를 연결하는데 자꾸만 오류가 떠서 해결해야하는 상황이었습니다.

 

TypeError: Cannot read properties of undefined (reading 'status')
ReferenceError: email is not defined
TypeError : Cannot read properties of undefined (reading 'body')

 

[시도 및 해결]

위 문제를 하나씩 해석하고 풀어나 갔습니다.

ejs에서 app.js 를 작성하는 방식이 view router에서 index.js를 작성하는 방식이 잘못된 것을 확인했습니다.

 

app.js

app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/views/static'));
app.use('/', viewRouter);

 

index.js

const express = require('express');
const router = express.Router();

router.get('/login', async (req, res) => {
  const { email, password } = req.body;
  return res.render('login');
});

module.exports = router;

 

 

login.js

document.getElementById('loginForm').addEventListener('submit', async (event) => {
  event.preventDefault(); // 이벤트 발생한 후 브라우저의 기본동작을 막음

  const email = document.getElementById('loginEmail').value;
  const password = document.getElementById('loginPassword').value;

  try {
    const response = await fetch('/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ email, password }),
    });

    if (response.ok) {
      window.location.href = './main.html';
    } else {
      const loginFailedModal = new bootstrap.Modal(document.getElementById('loginFailedModal'));
      loginFailedModal.show();
    }
  } catch (error) {
    console.log('로그인 오류', error);
  }
});

 

login.ejs

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css"
    />
    <!-- <script src="../views/static/css/" defer></script> -->
    <title>Login</title>
  </head>
  <body>
    <div class="container mt-5">
      <div class="row justify-content-center">
        <div class="col-md-6">
          <h2 class="mb-4">로그인</h2>
          <form id="loginForm">
            <div class="mb-3">
              <label for="loginEmail" class="form-label">이메일</label>
              <input
                type="email"
                class="form-control"
                id="loginEmail"
                placeholder="이메일을 입력하세요"
              />
            </div>
            <div class="mb-3">
              <label for="loginPassword" class="form-label">비밀번호</label>
              <input
                type="password"
                class="form-control"
                id="loginPassword"
                placeholder="비밀번호를 입력하세요"
              />
            </div>
            <button type="submit" class="btn btn-primary">로그인</button>
          </form>
        </div>
      </div>
    </div>
  </body>
</html>

 

 

[알게된 점]

뭔가 크게 잘못된 것 같지 않은데 숙성된 오류가 가끔씩 걸리는 것 같습니다.
코드작성을 하면서 하나씩 확인해봐야할 것 같습니다.