1. Express Router
- 들어오는 요청 경로를 라우터로 분리하는 역할
- 그렇게 함으로써 코드 복잡도를 낮출 수 있다.
- 즉, 들어오는 요청을 분리하지 않으면 많은 요청을 한 파일에 쓰기 코드가 복잡해지므로 router로 최상위 경로를 기준 삼아 분리하는 역할이다.
- express Router를 위한 파일을 따로 만들어 require를 해주고 app.use()를 이용해 사용하면 된다.
- app.use 매개변수로 최상위 경로를 정해주고 경로에 따라 그 다음 매개변수인 파일로 보내준다.
- router를 이용해 적혀있는 경로대로 찾아가 데이터를 전달 받고 데이터를 보내준다.
Client
axios.post("/api/login", {userid: userid, password:password}).then((res) => {
console.log(res.data);
const {result} = res.data
if(result === "success") {
// alert("로그인 성공");
window.location.href = "/home";
} else {
alert("로그인 실패");
}
})
axios.post('/api/regist', params).then((res) => {
const {result} = res.data;
if(result === "success") {
alert("회원가입에 성공하였습니다. 로그인 페이지로 이동합니다.")
window.location.href = "/";
} else {
alert("회원가입에 실패하였습니다.")
}
})
Server
const express = require("express");
const router = express.Router();
// /api/login POST 데이터를 전달 받는다.
router.post("/login", (req, res) => {
console.log("====================> [POST]/api/login call!!!");
console.log(req.body);
const {userid, password} = req.body
if(userid === "ssjj04022" && password == "12345") {
res.send({result: "success"});
} else {
res.send({result: "fail"})
}
})
// /api/regist POST 데이터를 전달 받는다.
router.post("/regist", (req, res) => {
console.log("====================> [POST]/api/regist call!!!")
console.log(req.body);
const {name, userid, password, year, month, day, gender} = req.body;
if(name && userid && password && year && month && day && gender) {
res.send({result: "success"});
} else {
res.send({result: "fail"})
}
})
module.exports = router
2. Server 에서 데이터와 이미지 보내기
- 이미지의 경우 프론트엔드 기준으로 보자면 현재 내 PC 이미지가 존재하지 않고 이미지는 원격 즉 서버에서 제공해야 한다.
- 그렇다면 이미지를 연결할 주소(link)는 원격, 즉 서버 주소여야 한다.
- 일단 먼저 제공한 이미지를 아래에 주소에 복사
- backend/public/images 에 파일 복사
- express 서버에서 기본적으로 제공되는 공개된 메인 url은 public 부터 시작
- app.use(express.static(path.join(__dirname, 'public')))에 의하여 설정
- public 밑에 존재하는 이미지를 서버에서 사용
- 그리고 image 주소 /image/game-1.jpg 이런 식으로 변경
- 그래서 서버쪽에서 데이터와 함께 이미지도 클라이언트에게 같이 보냄
- 밑에 처럼 배열 안에 JSON 데이터로 설정해서 요청에 따라 클라이언트 쪽에 데이터를 보내고 클라이언트 쪽에서 배열 반복 문을 통해 데이터들을 원하는 곳에 삽입하면 된다.
** 컴포넌트 속성으로 value에 JSON 데이터로 값을 주고 그 컴포넌트 안에서 props.value로 값을 주게 된다면 이름이 똑같은 JSON 값으로 쉽게 받을 수 있다. **
<CardBox key={item.no} value={item} onRefresh={onRefreshHome}/>
const CardBox = (props) => {
const {no, likecount, title, subtitle, tags, url, text, image} = props.value
}
Client
import { Image, Title, Subtitle, Button, Input } from "./Component"
import Header from './Header.jsx'
import EDU_ICON from '../images/edu_icon.png'
import MORE_ICON from '../images/more.png'
import MAIN_IMAGE_1 from '../images/game-1.jpg'
import MAIN_IMAGE_2 from '../images/game-2.jpg'
import MAIN_IMAGE_3 from '../images/game-3.jpg'
import HOME_ICON from '../images/home.png'
import YOUTUBE_ICON from '../images/youtube.png'
import PEOPLE_ICON from '../images/people.png'
import axios from "axios"
import { useEffect, useState } from "react"
export default function Home(props) {
const [array, setArray] = useState("");
// 이 홈이라는 것이 생성될 떄 딱 한번(didmount와 같은)
useEffect(() => {
axios.get("/api/home", {}).then((res) => {
// console.log(res.data);
setArray(res.data.result)
})
}, [])
const onRefreshHome = () => {
console.log("onfresh")
axios.get("/api/home", {}).then((res) => {
// console.log(res.data);
setArray(res.data.result)
})
}
// const value = {title, subtitle, tags, url, text}
return (
<>
<Header name="home" />
<section className="home-layer">
<ul className="list">
{array && array.map((item, index) => {
return <CardBox key={item.no} value={item} onRefresh={onRefreshHome}/>
})}
</ul>
</section>
</>
)
}
const CardBox = (props) => {
const {no, likecount, title, subtitle, tags, url, text, image} = props.value
const onClickLike = () => {
// console.log(props.value)
axios.put("/api/home/like", {no: no, like: 1}).then(res => {
props.onRefresh();
})
}
const onClickComment = () => {
}
return <li>
<div className="card">
<div className="head">
<div>
<Image src={EDU_ICON} alt="광고 아이콘" />
<span className="title">{title}</span>
<Image className="more" src={MORE_ICON} alt="더보기 메뉴" />
</div>
<div className="text">
<p>{subtitle}</p>
<p className="blue">{tags}</p>
</div>
</div>
<div className="body">
<div className="image">
<Image src={image} alt="광고 메인 이미지" />
</div>
<div className="text">
<div>
<p className="grey sm">{url}</p>
<p className="bold">{text}</p>
<p className="grey"></p>
</div>
<button>더 알아보기</button>
</div>
</div>
<div className="foot">
<div className="btn-box active">
<div>
<Image src={HOME_ICON} alt="홈 바로가기" />
<span className="btn-text" onClick={onClickLike}>좋아요({likecount})</span>
</div>
</div>
<div className="btn-box">
<div>
<Image src={YOUTUBE_ICON} alt="동영상 바로가기" />
<span className="btn-text" onClick={onClickComment}>댓글 달기</span>
</div>
</div>
<div className="btn-box">
<div>
<Image src={PEOPLE_ICON} alt="사용자 바로가기" />
<span className="btn-text">공유 하기</span>
</div>
</div>
</div>
</div>
</li>
}
Server
// 데이터를 배열로 안에 값은 JSON 데이터로
const array = [
{
no: 1,
title: "에듀윌",
subtitle: "🚨기간한정 특별 이벤트🚨 초시생 필수템, 만화입문서 무료배포!",
tags: "#합격자수1위 #에듀윌 #공인중개사",
url: "EDUWILL.NET",
text: "입문교재 선착순 무료신청☞ 합격자 수 1위 에듀윌 공인중개사",
image: "/images/game-1.jpg",
likecount: 1
},
{
no: 2,
title: "코리아아이티",
subtitle: "🚨기간한정 특별 이벤트🚨 프론트엔드 5개월차 수업!",
tags: "#합격자수1위 #에듀윌 #공인중개사",
url: "KOREATIT.NET",
text: "녹화 동영상 무료 제공! ☞ 합격자 수 1위 에듀윌 공인중개사",
image: "/images/game-2.jpg",
likecount: 2
},
{
no: 3,
title: "코리아아이티aaaa",
subtitle: "🚨기간한정 특별 이벤트🚨 aaaaaaa!",
tags: "#합격자수1위 #에듀윌 #공인중개사",
url: "KOREATIT.NET",
text: "aaaaaaaaaaaaa! ☞ 합격자 수 1위 에듀윌 공인중개사",
image: "/images/game-3.jpg",
likecount: 3
}
]
router.get("/home", (req, res) => {
console.log("===================> [GET]/api/home call!!!");
console.log(req.query)
res.send({result: array})
})
router.put("/home/like", (req, res) => {
console.log("===================> [PUT]/api/home/like call!!!");
console.log(req.body)
const {no, like} = req.body;
const data = array.find(item => item.no === no);
data.likecount = data.likecount + like
console.log(array)
res.send({result: "success"});
})
module.exports = router
'FrontEnd > Node.js' 카테고리의 다른 글
[Node] Project - Login, Regist (0) | 2022.12.01 |
---|---|
[Node] Project 구성 (0) | 2022.12.01 |
[Node] callback, Promise, Async & Await (0) | 2022.12.01 |
[Node] Node.js Client-Server 데이터 전달 (0) | 2022.11.25 |
[Node] Node.js 스프레드 연산자(Spread Operator) (0) | 2022.11.25 |