------------------------------------------------------
글목록 GET => http://1.234.5.158:23000/board101/select.json?page=1&text=
글쓰기 POST => http://1.234.5.158:23000/board101/insert.json => key 정보 : title, content, writer
글수정 PUT => http://1.234.5.158:23000/board101/update.json?no=113 => key 정보 : title, content, writer
글삭제 DELETE => http://1.234.5.158:23000/board101/delete.json?no=113
글1개조회 GET => http://1.234.5.158:23000/board101/selectone.json?no=668
조회수증가 PUT => http://1.234.5.158:23000/board101/updatehit.json?no=668
------------------------------------------------------
await axios.get(url, {headers});
await axios.post(url, body, {headers});
await axios.put(url, body, {headers});
await axios.delete(url, {headers:headers, data:body});
------------------------------------------------------
물품목록 => http://1.234.5.158:23000/item101/selectlistpage.json?page=1
물품등록 => http://1.234.5.158:23000/item101/insert.json => key 정보: name, price, content, quantity, image
물품1개조회 => http://1.234.5.158:23000/item101/selectone.json?no=1
-------------------------------------------------------
// 파일명 : boardone1.html
어제 수업 내용에서 삭제, 수정, 이전글, 다음글 기능 추가
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>게시판내용</title>
<style>
.container {
width : 800px;
margin : 0px auto;
padding : 10px;
border : 3px solid #cccccc;
}
</style>
</head>
<body>
<div class="container">
<h3>게시물 내용</h3>
<hr />
<div id="div"></div>
<a href="/board1.html"><button>목록</button></a>
<button onclick="handleUpdate()">수정</button>
<button onclick="handleDelete()">삭제</button>
<button onclick="handlePrev()">이전글</button>
<button onclick="handleNext()">다음글</button>
</div>
<script src="js/axios.min.js" type="text/javascript"></script>
<script>
const div = document.getElementById('div');
const href = new URL(window.location);
const no = href.searchParams.get("no");
console.log(no);
if(no === null){
alert('잘못된 접근입니다.');
window.location.href="/board1.html";
}
// 함수 외부에 있는 변수, 모든 함수에서 사용가능함!
// const a=13; a는 13으로 계속 사용해야함, 못바꿈 -> 상수:초기값 반드시 설정해야함
// let b=14; b는 초기값이 14고 게속 바꿔서 사용가능함 -> 변수:초기값 설정이 필수아님
let prev;
let next;
//이전글 번호, 다음글 번호를 변수로 받아옴
function handleUpdate() {
// 수정할 수 있는 화면으로 전환함.
window.location.href=`/boardupdate1.html?no=${no}` ;
}
async function handleDelete() {
const result = confirm('삭제할까요?'); //삭제하기전 확인
console.log(result); // true, false
if(result === true) { // 확인버튼을 클릭한 경우
const url = `http://1.234.5.158:23000/board101/delete.json?no=${no}`;
const headers = {"Content-Type":"application/json"};
const body = {};
const {data} = await axios.delete(url, {headers:headers, data:body});
// 삭제하는 스크립트
console.log(data);
if(data.status === 200) {
alert('삭제 되었습니다.');
window.location.href="/board1.html";
// 삭제후 게시판 목록으로 이동
}
}
}
function handlePrev() {
// 주소를 바꾸고 엔터키 누름
if(prev !== 0) { // 이전글 번호가 0이 아니면
window.location.href=`/boardone1.html?no=${prev}`;
// 페이지 이동하지 않고 no만 바뀌는것
}
else {
alert('이전글이 없습니다.');
}
}
function handleNext() {
if(next !== 0) { // 다음글 번호가 0이 아니면
window.location.href=`/boardone1.html?no=${next}`;
}
else {
alert('다음글이 없습니다.');
}
}
// 함수 생성, 자동호출되지 않음
async function handleData() {
const url = `http://1.234.5.158:23000/board101/selectone.json?no=${no}`;
const headers = {"Content-Type":"application/json"} ;
const { data } = await axios.get( url, {headers} )
// 글목록 불러오는 스크립트
//1개의 게시물 정보, 이전글 번호, 다음글 번호
console.log(data);
if(data.status === 200) {
div.innerHTML +=
`<p>글번호 : ${data.result._id}</p>` +
`<p>글제목 : ${data.result.title}</p>` +
`<p>글내용 : ${data.result.content}</p>` +
`<p>작성자 : ${data.result.writer}</p>` +
`<p>조회수 : ${data.result.hit}</p>`;
// data는 handleData에서 불러온 값
// data에 포함된 정보를 다른 함수에서 사용하기 위해서 외부 변수에 저장함
// 외부에 두는 변수를 상태변수라고한다.
prev = data.prevNo;
next = data.nextNo;
}
}
//호출함
handleData();
</script>
</body>
</html>
// 파일명 : boardupdate1.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>게시판수정</title>
<style>
.container {
width : 500px;
padding : 10px;
border : 3px solid #cccccc;
}
.lbl {
display : inline-block;
width : 100px;
}
// 아이템은 공간을 주기 위해 만든것
.item {
margin-bottom: 5px;
}
</style>
</head>
<body>
<div class="container">
<h3>글수정</h3>
<hr />
<div class="item">
<label class="lbl">글번호</label>
<input type="text" class="input" readonly />
// 글번호, 조회수, 등록일은 수정되면 안되므로 readonly
</div>
<div class="item">
<label class="lbl">*제목</label>
<input type="text" class="input" />
</div>
<div class="item">
<label class="lbl">*글내용</label>
<textarea rows="6" class="input"></textarea>
</div>
<div class="item">
<label class="lbl">*작성자</label>
<input type="text" class="input" />
</div>
<div class="item">
<label class="lbl">조회수</label>
<input type="text" class="input" readonly />
</div>
<div class="item">
<label class="lbl">등록일</label>
<input type="text" class="input" readonly />
</div>
<div class="item">
<label class="lbl"></label>
<button onclick="handleUpdate()">수정하기</button>
<a href="/board1.html"><button>목록으로</button></a>
</div>
</div>
<script src="js/axios.min.js" type="text/javascript"></script>
<script>
// 자동으로 실행됨.(준비물, 공통변수, 태그연결)
// no 출력
const href = new URL(window.location);
const no = href.searchParams.get("no");
// 여러개를 연결함(6개) input[0], input[1], ... input[5]
const input = document.getElementsByClassName('input');
// 수정하려면 데이터가 미리 나와있어야 하는데 이때 이전의 데이터를 그대로 쓰는것이 아니라 새로 불러와야한다.
// 수정하는 페이지로 넘어가는 사이에 데이터값이 바뀔수 있으므로!
// 따라서 게시글 번호만 수정 페이지에 넘기고 수정 페이지에서 게시글 번호로 데이터를 다시 받아야한다.
// 글번호를 이용해서 게시물1개의 정보 가져오기
async function handleData() {
const url = `http://1.234.5.158:23000/board101/selectone.json?no=${no}`;;
const headers = {"Content-Type":"application/json"};
const { data } = await axios.get(url, {headers});
console.log('handleData', data);
// 모든 data를 보면 복잡하니까 handleData에서 이용한 data만 출력
if(data.status === 200){
input[0].value = data.result._id;
input[1].value = data.result.title;
input[2].value = data.result.content;
input[3].value = data.result.writer;
input[4].value = data.result.hit;
input[5].value = data.result.regdate;
}
}
handleData(); // 함수 자동 실행
// 함수, 호출되지 않으면 실행되지 않음.
async function handleUpdate() {
const url = `http://1.234.5.158:23000/board101/update.json?no=${no}`;
const headers = {"Content-Type":"application/json"};
// 변경할 내용들 전송, key는 변경불가
const body = {
title : input[1].value,
content : input[2].value,
writer : input[3].value
};
const { data } = await axios.put(url, body, {headers});
console.log('handleUpdate', data);
if(data.status === 200){
alert('수정되었습니다.');
window.location.href = `/boardone1.html?no=${no}`;
}
}
</script>
</body>
</html>
// 파일명 : itemlist1.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>물품목록</title>
<style>
.container {
width: 800px;
margin : 2px;
border : 2px solid #cccccc;
}
header {
background-color: rgb(163, 174, 174);
text-align : center;
padding : 20px;
color : azure;
}
footer {
background-color: rgb(110, 117, 117);
text-align : center;
padding : 20px;
color : azure;
}
section {
display : grid;
/* 가로로 4부분으로 구분 */
grid-template-columns : 1fr 1fr 1fr 1fr;
/* 최소크기, 최대크기 */
grid-auto-rows : minmax(240px, auto);
}
/* 이미지에 테두리 넣기 */
.box {
margin : 5px;
padding : 5px;
border : 1px solid #efefef;
}
/* a태그 스타일 바꾸기 */
a {
text-decoration: none;
color: #111111;
}
/* a태그에 커서를 올렸을때 스타일 바꾸기 */
a:hover .box {
color : red;
border : 1px solid red;
}
</style>
</head>
<body>
<div class="container">
// div class="header"로 쓰다가 더 간편한 형태로 바뀐것
<header>
<h3>header 영역</h3>
</header>
<section id="section">
</section>
<footer>
<h3>footer 영역</h3>
</footer>
</div>
<script src="js/axios.min.js" type="text/javascript"></script>
<script>
// 자동실행, 공통역역
const section = document.getElementById('section');
// 물품의 목록을 가져오는 함수
async function handleData() {
const url = `http://1.234.5.158:23000/item101/selectlistpage.json?page=1`;
const headers = {"Content-Type":"application/json"};
const { data } = await axios.get(url, {headers});
console.log(data);
if(data.status === 200) {
// data.result = [{},{},{} ... {}]
// 배열된 각각의 data.result들을 tmp로 가져옴
for(let tmp of data.result) {
console.log(tmp);
section.innerHTML +=
`<a href="/itemcontent1.html?no=${tmp._id}">` +
`<div class="box">`+
`<img src="${tmp.img}" style="width:100%;height:150px;" />`+
`<p>${tmp.name}</p>`+
`<p>${tmp.price}</p>`+
`</div>`+
`</a>`;
}
}
}
handleData();
</script>
</body>
</html>
// 파일명 : iteminsert1.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>물품등록</title>
<style>
.container {
width : 800px;
margin : 2px;
border : 3px solid #cccccc;
}
header {
background-color: rgb(255, 247, 176);
text-align : center;
padding : 20px;
color : rgb(195, 0, 255);
}
footer {
background-color: rgb(195, 0, 255);
text-align : center;
padding : 20px;
color : rgb(255, 247, 176);
}
section {
display : grid;
grid-template-columns: 150px auto;
}
nav {
padding : 20px;
background-color: rgba(233, 187, 255, 0.377);
}
article {
padding : 30px;
background-color: rgba(255, 246, 164, 0.397);
}
.lbl {
margin : 10px ;
display : inline-block ;
width : 100px ;
}
ul {
list-style-type : none;
padding : 0;
}
a {
text-decoration: none;
color: rgb(40, 0, 85);
}
</style>
</head>
<body>
<div class="container">
<header>
<h3>판매자 페이지</h3>
</header>
<section>
<nav>
// 목록화 할때는 ul, li 태그 이용
<ul>
<li><a href="/iteminsert1.html">물품등록</a></li>
<li><a href="/itemseller1.html">물품목록</a></li>
</ul>
</nav>
<article>
<div>
<label class="lbl">물품명</label>
<input type="text" id="name" placeholder="물품명을 입력하세요." />
</div>
<div>
<label class="lbl">물품설명</label>
<textarea rows="6" id="content" cols="22" style="resize: none;" placeholder="물품설명을 입력하세요."></textarea>
</div>
<div>
<label class="lbl">가격</label>
<input type="number" id="price" value="1" />
// 숫자만 입력, 기본값 1
</div>
<div>
<label class="lbl">수량</label>
<input type="number" id="quantity" value="1" />
</div>
<div>
<label class="lbl">이미지</label>
<input type="file" id="file" onchange="handleImage(this)" />
</div>
<div>
<label class="lbl"></label>
<button onclick="handleInsert()">등록하기</button>
</div>
</article>
</section>
<footer>
<h3>footer 영역</h3>
</footer>
</div>
<script src="js/axios.min.js" type="text/javascript"></script>
<script>
// 공통영역
// id로 받아서 하나하나 다 찾는것. class였다면 한줄로 가능.
const name = document.getElementById('name');
const content = document.getElementById('content');
const price = document.getElementById('price');
const quantity = document.getElementById('quantity');
const file = document.getElementById('file');
// 함수
async function handleInsert() {
const url = `http://1.234.5.158:23000/item101/insert.json`;
// 이미지 없으면 => const headers = {"Content-Type":"application/json"};
const headers = {"Content-Type":"multipart/form-data"};
// 이전에 썼던 스크립트들은 백엔드에서 받아오는것
// 이건 내 컴퓨터에 있는 이미지 파일을 띄우기 위해서 웹브라우저가 제공하는 것
const body = new FormData();
body.append("name", name.value);
body.append("content", content.value);
body.append("price", price.value);
body.append("quantity", quantity.value);
body.append("image", file.files[0]);
console.log('입력한 물품명', name.value);
console.log('입력한 이미지', file.files[0]);
const { data } = await axios.post( url, body, {headers} );
console.log(data);
if(data.status === 200) {
alert('등록되었습니다.');
window.location.href='/itemlist1.html';
}
}
</script>
</body>
</html>
// 파일명 itemcontent1.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>물품1개정보</title>
<style>
.container{
width : 800px;
}
header {
background-color: rgb(163, 174, 174);
text-align : center;
padding : 20px;
color : azure;
}
footer {
background-color: rgb(110, 117, 117);
text-align : center;
padding : 20px;
color : azure;
}
section {
display : grid;
grid-template-columns: 1fr 1fr;
}
.item {
padding : 20px;
border : 1px solid #cccccc;
}
</style>
</head>
<body>
<div class="container">
<header>
<h3>header영역</h3>
</header>
<section>
<div class="item"></div>
<div class="item"></div>
</section>
<footer>
<h3>footer영역</h3>
</footer>
</div>
<script src="js/axios.min.js" type="text/javascript"></script>
<script>
// 공통영역
//item[0], item[1] -> 배열한것처럼 취급
const item = document.getElementsByClassName('item');
const href = new URL(window.location);
const no = href.searchParams.get("no");
console.log(no);
// 함수영역
async function handleData() {
const url = `http://1.234.5.158:23000/item101/selectone.json?no=${no}`;
const headers = {"Content-Type":"application/json"};
const { data } = await axios.get(url, {headers});
console.log(data);
if(data.status === 200){
item[0].innerHTML += `<img src="${data.result.img}" style="width:100%" />`;
item[1].innerHTML += `<p>물품명 : ${data.result.name}</p>`;
item[1].innerHTML += `<p>가격 : ${data.result.price}</p>`;
item[1].innerHTML +=
`수량 : <select>`+
`<option>1</option>`+
`<option>2</option>`+
`<option>3</option>`+
`<option>4</option>`+
`<option>5</option>`+
`</select>`;
item[1].innerHTML += `<p><button>주문하기</button></p>`;
}
if(no === null) {
alert('잘못된 접근입니다.') ;
window.location.href="/itemlist1.html";
}
}
handleData();
</script>
</body>
</html>
첫날은 html과 css약간이라 쉬웠고 둘째날은 객체 처음 보고 멘붕, 셋째날 역시 변수 선언하는것과 라이브러리를 이용해서 데이터를 가져오는 형식이 너무 낯설어서 이해한다고 머리 터졌는데 넷째날이 되자 이때까지 한것의 반복이라는 느낌이 들고 받아들이기 어렵지 않아짐. 코드 하나하나 뜯어서 이해한다기 보다는 이 코드가 여기 왜 들어갔고 어떤 의미인지를 파악한다고 생각하고 접근하자. 알고보면 별거 아녀~