onChange
이벤트 핸들러에 연결된 함수가 실행됩니다.value
를 setId
를 통해 업데이트 합니다.onChange
이벤트 핸들러에 연결된 함수가 실행됩니다.value
를 setPw
를 통해 업데이트 합니다.onClick
이벤트 핸들러에 연결된 함수가 실행됩니다.fetch
함수를 통해 server에 요청(Request)을 보냅니다.API 주소
입니다.HTTP 통신에 관한 내용
입니다. method
에는 GET
, POST
, PATCH
등 HTTP method를 입력합니다.body
에는 JSON 형태로 주고 받을 데이터를 넣습니다.JSON.stringify()
라는 메서드를 활용해서 포맷을 기존의 javascript object에서 JSON String으로 변환해줍니다.then()
메서드는 Promise 객체에 사용할 수 있는 메서드 입니다. 위 예제 코드를 보면, then()
메서드를 fetch 함수의 실행 결과에 체이닝 하고 있는데, 이는 비동기로 처리된 fetch 함수의 결과 값이 들어오면 then 메서드의 액션을 실행 하라는 의미입니다..then((response) => response.json())
첫 번째 then에서는 server에서 보내준 response를 Object 형태로 변환합니다..then((result) => console.log("결과: ", result));
두 번째 then에서는 object로 변환한 response를 console.log로 확인합니다. 위 예제 코드에서는 콘솔을 출력하고 있지만, 사실 이 부분에 분기 처리하는 로직이 구현 됩니다. 예를 들어,로그인 성공하면 main 페이지로 이동
로그인 실패하면 alert 창에 "아이디 / 비밀번호를 확인해주세요." 띄우기
와 같은 로직이 들어가게 됩니다.
http://10.58.8.116:8000/users/signup
과 같이 http://
, IP주소
, 포트번호
, 엔드포인트
다 작성이 잘 되었는지 확인.회원가입 페이지를 따로 구현하지 않아서 로그인 페이지를 사용하되, 함수 onClick시 사용될 함수만 교체하며 진행. 백엔드에서 결과를 객체형태(json)로 반환하는데, 이 객체에 접근해서 메시지를 확인한 후 다음 로직으로 넘어가도록 할 수 있음.(ex. alert, useNavigate)
const signup = () => {
fetch('http://**.**.*.**:8000/users/signup', {
method: 'POST',
body: JSON.stringify({
email: idInput,
password: pwInput,
}),
})
.then(response => response.json())
.then(result => {
//console.log('결과: ', result.message)
if (result.message === 'EMAIL_ALREADY_EXISTS') {
console.log('Error : Duplicated');
}
});
};
const login = () => {
fetch('http://**.**.*.**:8000/users/login', {
method: 'POST',
body: JSON.stringify({
email: idInput,
password: pwInput,
}),
})
.then(response => response.json())
.then(result => {
//console.log('결과: ', result.message)
if (result.message === 'SUCCESS') {
console.log('login SUCCESS');
}
});
};
useEffect(() => {
fetch('http://localhost:3000/data/commentData.json', {
method: 'GET' // GET method는 기본값이라서 생략이 가능합니다.
}) // 예시코드에서는 이해를 돕기 위해 명시적으로 기입해뒀습니다.
.then(res => res.json())
.then(data => {
setCommentList(data);
});
},[])
const COMMENT_LIST = [
{
id: 1,
userName: 'wecode',
content: 'Welcome to world best coding bootcamp!',
isLiked: true
},
{
id: 2,
userName: 'joonsikyang',
content: 'Hi there.',
isLiked: false
},
{
id: 3,
userName: 'jayPark',
content: 'Hey.',
isLiked: false
}
];
export default COMMENT_LIST;
import React from 'react';
import Comment from './Comment/Comment';
import COMMENT_LIST from './commentData';
import './CommentList.scss';
function CommentList() {
return (
<div className="commentList">
<h1>댓글</h1>
<ul>
{COMMENT_LIST.map(comment => {
return (
<Comment
key={comment.id}
name={comment.userName}
comment={comment.content}
/>
);
})}
</ul>
</div>
);
}
export default CommentList;