nodejs가 설치된 backend 폴더로 이동하여 postgresql 설치
npm install pg
nodejs가 설치된 backend 폴더에 server.js를 생성하여 코드를 다음과 같이 작성한다.
nodejs와 express를 연동하여 서버를 미리 생성해놔야 한다! 필슈필수
- nodejs와 express 연동
🔗 https://velog.io/@soyul2823/vuejs-2-nodejs-express-서버-생성
- server.js
var express = require('express');
const { Pool } = require('pg')
var app = express();
const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'postgres',
password: '1234',
port: 5432,
}) //DB정보
app.post('/api/login', async (req, res) => { //로그인 api 설정
const { userId, userPw } = req.body; //userId와 userPw를 body에서 받아온 아이디와 비밀번호로 설정
try {
const result = await pool.query('SELECT * FROM public.user WHERE id=$1 AND pw=$2', [userId, userPw]); //아이디와 비밀번호가 일치하는지 확인
if (result.rows.length > 0) {
res.json({ success: true});
} else {
res.json({ success: false});
}
} catch (err) {
console.error(err);
res.status(500).json({ success: false, message: 'Server error' });
}
});
app.listen(3000, function() {
console.log('App is listening on port 3000');
}); //port 번호 3000번으로 서버 접속
vue 프로젝트가 생성되어있는 frontend 폴더에 login.vue를 생성한다.
- login.vue
<template>
<form id="loginForm" @submit.prevent="onSubmit">
<!-- 폼 유효성 검사를 하기 위해 @submit.prevent 설정하여 onSubmit 함수를 실행 -->
<input class="form-control" id="id" type="text" minlength="4"
maxlength="20" placeholder=""
v-model="userId"/>
<label for="name">아이디</label>
<input class="form-control" id="pw" type="password" minlength="8"
maxlength="16" placeholder=""
v-model="userPw"/>
<label for="pw">비밀번호</label>
<button class="btn btn-primary btn-lg" id="loginBtn" type="submit">로그인</button>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
const router = useRouter();
//v-model로 설정한 userId와 userPw를 ref를 사용하여 초기화한다.
const userId = ref('');
const userPw = ref('');
const login = async () => {
try {
const response = await axios.post('http://localhost:3000/api/login', { // 서버에서 설정한 로그인 api를 post로 보내기 위해 axios 사용
//login api로 userId.value와 userPw.value 값을 userId와 userPw로 보내준다.
userId: userId.value,
userPw: userPw.value,
});
if (response.data.success === true) { //로그인 성공했을 경우
router.push({path: '/main'}) //main 페이지로 router를 통하여 페이지 이동
} else {
alert('아이디와 비밀번호가 일치하지 않습니다.')
}
} catch (err) {
console.error('Server error:', err);
alert("서버 오류입니다. 잠시 후 다시 시도해주세요.")
}
};
const onSubmit = (event: Event) => {
event.preventDefault();
//유효성 검사 코드 작성
login();
};
</script>
여기서 ref를 사용하는 이유는 반응형 데이터를 만들기 위해서 쓰인다.
아이디, 비밀번호 유효성 검사할 때 사용한다.
input 태그와 label 태그 밑에 div를 추가하여 유효성 검사 메세지를 출력할 수 있다.
위의 코드에서는 유효성검사 코드는 생략하였음 왜냐면 코드가 너무 길기 때무네!
다음에 포스팅해야디
reactive를 사용할 수도 있다.
import { reactive } from 'vue';
const user = reactive({
userId: ''
userPw: ''
});