참고
https://iamiwill.tistory.com/17
프론트엔드
import axios from 'axios';
import React, { useState } from 'react';
import Button from 'react-bootstrap/Button';
import Col from 'react-bootstrap/Col';
import Form from 'react-bootstrap/Form';
import Row from 'react-bootstrap/Row';
const SignIns: React.FC = () => {
const [name, setName] = useState("");
const [password, setPassword] = useState("");
const handleSubmit = () => {
if (name === "" || password === "") {
alert("빈칸을 모두 채우시오.");
return;
}
let body = {
user_name: name,
user_password: password
};
axios
.post("http://localhost:3000/user/login", body)
.then((res) => console.log(res));
};
return (
<div>
<Form onSubmit={handleSubmit}>
<div className="mb-3">로그인</div>
<Form.Group as={Row} className="mb-3" controlId="formHorizontalEmail">
<Form.Label column sm={2}>
ID
</Form.Label>
<Form.Control type="name" placeholder="name" onChange={(e) => {setName(e.target.value)}}/>
</Form.Group>
<Form.Group as={Row} className="mb-3" controlId="formHorizontalEmail">
<Form.Label column sm={2}>
Password
</Form.Label>
<Form.Control type="password" placeholder="password" onChange={(e) => {setPassword(e.target.value)}}/>
</Form.Group>
<Form.Group as={Row} className="mb-3">
<Col sm={{ span: 10, offset: 2 }}>
<Button
type="submit"
>
Log in
</Button>
</Col>
</Form.Group>
</Form>
</div>
)
}
export default SignIns;
백엔드
router.post("/login", async (req, res, next) => {
console.log(req.body);
const {user_name, user_password} = req.body;
try {
const confirmUser = await client.query(`SELECT * FROM user_account WHERE user_name=$1`, [user_name,]);
if (confirmUser.rows.length !== 0) {
let validatePassword = bcrypt.compare(user_password, confirmUser.rows[0].password_hash)
if(!validatePassword){
return res.status(409).json({
error: "비밀번호가 틀렸습니다.",
});
}
res.status(200).json({message: 'Login successful'})
} else {
return res.status(409).json({
error: "아이디가 존재하지 않습니다.",
});
}
} catch (err) {
console.error(err);
}
});
confirmUser를 출력해보면 rows 안에 알맞은 데이터가 들어있다. 이 rows는 user_name을 unique로 만들었기 때문에 크기가 0 또는 1인 배열이 된다.
그래서 데이터에 접근할 때 confirmUser.rows[0].password_hash로 접근할 수 있다.
로그인과 회원가입에 사용하는 user_account table
create table user_account (
user_id serial PRIMARY KEY,
user_name varchar(80) unique not null,
password_hash varchar(128) not null,
join_date date not null default now()
);
'개발 > React(ReactNative)' 카테고리의 다른 글
[reactnative] goback 후에 useeffect가 작동하지 않음 (1) | 2023.10.04 |
---|---|
ReactNative 네비게이션 (0) | 2023.09.14 |
[ReactNative] react-hook-form (0) | 2023.09.06 |
[React] react 회원가입 폼 만들기 (0) | 2023.07.26 |