[React] Lamp 쇼핑몰 구현하기 8 (깃허브 주소 및 최종 코드)
client-github
https://github.com/7ingout/lamp-shopping-client
GitHub - 7ingout/lamp-shopping-client: 리액트 조명 쇼핑몰 클라이언트
리액트 조명 쇼핑몰 클라이언트. Contribute to 7ingout/lamp-shopping-client development by creating an account on GitHub.
github.com
server-github
https://github.com/7ingout/lamp-shopping-server
GitHub - 7ingout/lamp-shopping-server: 조명 쇼핑몰 서버입니다.
조명 쇼핑몰 서버입니다. Contribute to 7ingout/lamp-shopping-server development by creating an account on GitHub.
github.com
LAMP-SHOPPING-SERVER
config
config/config.json
{
"development": {
"storage": "./database.sqlite3",
"dialect": "sqlite"
},
"test": {
"storage": "memory",
"dialect": "sqlite"
},
"production": {
"storage": "./database.sqlite3",
"dialect": "sqlite"
}
}
models
models/index.js
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
models/products.js
// Common.js 구문 내보내기
// module.exprors
// 테이블을 모델링하는 파일
module.exports = function (sequelize, DataTypes) {
// 컬럼 name, price, imageUrl, seller
// 제약조건 allowNull: 컬럼의 값이 없어도 되는지 여부 (default: true)
const product = sequelize.define('Product', {
name: {
type: DataTypes.STRING(20),
allowNull: false
},
price: {
type: DataTypes.INTEGER(20),
allowNull: false
},
imageUrl: {
type: DataTypes.STRING(500),
},
seller: {
type: DataTypes.STRING(200),
allowNull: false
},
description: {
type: DataTypes.STRING(500),
allowNull: false
}
});
return product;
}
index_node.js
// node는 CommomJS 문법을 사용
// import require()
const http = require('http');
// 본인컴퓨터의 주소를 의미함 127.0.0.1
const hostname = "127.0.0.1";
const port = 8080;
// 서버만들기 createServer(f(req, res))
const server = http.createServer(function(req,res){
// 요청정보 req
// 응답해줄게 res
// console.log(req);
const path = req.url;
const method = req.method;
if (path === "/products") {
if (method === "GET") {
// 응답을 보낼 때 타입을 제이슨 객체를 헤더에 보낼거야
res.writeHead(200, {'Content-Type': 'application/json'})
// js 배열을 json형태로 변경해서 products에 담기
const products = JSON.stringify([
{
name: "거실조명",
price: 50000,
},
{
name: "어린이조명",
price: 50000,
}
])
res.end(products);
}
}
console.log(path);
console.log(method);
res.end("Hello Client");
})
// listen은 대기 호스트네임과 포트번호로 요청을 기다림
server.listen(port, hostname);
console.log('조명쇼핑몰 서버가 돌아가고 있습니다.');
index.js
const express = require("express");
const cors = require("cors");
const app = express();
// const port = 3000;
// 헤로쿠에서 포트 지정하는게 있으면 그 번호를 사용
// 없으면 8080포트를 사용
const port = process.env.PORT || 8080;
const models = require('./models');
// 업로드 이미지를 관리하는 스토리지 서버를 연결 -> multer를 사용하겠다
const multer = require("multer");
// 이미지 파일이 요청 오면 어디에 저장할건지 지정
const upload = multer({
storage: multer.diskStorage({
destination: function(req, file, cb) {
// 어디에 저장할거냐? upload/
cb(null, 'upload/')
},
filename: function(req, file, cb){
// 어떤 이름으로 저장할거야?
// file 객체의 오리지널 이름으로 저장하겠다.
cb(null, file.originalname)
}
})
})
// json형식의 데이터를 처리할 수 있게 설정
app.use(express.json());
// 브라우저 cors 이슈를 막기 위해 사용(모든 브라우저의 요청을 일정하게 받겠다)
app.use(cors());
// upload 폴더에 있는 파일에 접근할 수 있도록 설정
app.use("/upload", express.static("upload"));
// 요청처리
// app.메서드(url, 함수)
// 이미지파일이 post로 요청이 왔을 때 upload라는 폴더에 이미지를 저장하기
// 이미지가 하나일 때 single
app.post('/image', upload.single('image'), (req, res)=>{
const file = req.file;
console.log(file);
res.send({
imageUrl: "https://lamp-shopping-server-7ingout.herokuapp.com/"+file.destination+file.filename
})
})
app.get('/products',async(req,res)=>{
// 데이터베이스 조회하기
models.Product.findAll()
.then(result=> {
// console.log("제품전체조회", result);
res.send(result);
})
.catch(e=>{
console.error(e)
res.send("파일 조회에 문제가 있습니다.")
})
})
// method는 get이고 오고 url은 /product/2 로 요청이 온 경우
app.get('/product/:id', async (req, res) => {
const params = req.params;
// const { id } = params;
// 하나만 조회할때는 findDone -> select문
models.Product.findOne({
// 조건절
where: {
id: params.id
}
})
.then(result=>{
res.send(result);
})
.catch(e=>{
console.log(e)
res.send("상품 조회에 문제가 생겼습니다.")
})
// const product = {
// id: id,
// name: "서버에서 보내는 이름",
// price: 50000,
// imgsrc:"images/products/product4.jpg",
// seller: "green",
// }
// res.send(product);
});
// app.post('/green', async (req, res)=>{
// console.log(req);
// res.send('그린 게시판에 게시글이 등록되었습니다.');
// });
// 상품 등록
app.post("/products", (req, res)=> {
// http body에 있는 데이터
const body = req.body;
// body객체에 있는 값을 각각 변수에 할당
const { name, price, seller, imageUrl, description } = body;
if(!name || !price || !seller) {
res.send("모든 필드를 입력해주세요");
}
// Product테이블에 레코드를 삽입
else {
models.Product.create({
name,
price,
seller,
imageUrl,
description
}).then(result=>{
console.log("상품 생성 결과 :", result);
res.send({
result
})
})
.catch(e=>{
console.error(e);
res.send("상품 업로드에 문제가 생겼습니다.")
})
}
})
// delete 삭제하기
app.delete('/product/:id', async (req, res)=>{
const params = req.params;
models.Product.destroy({ where: {id: params.id} })
.then( res.send("상품이 삭제되었습니다."))
})
// 실행
app.listen(port, ()=>{
console.log('쇼핑몰 서버가 동작중입니다.');
// sequelize와 데이터베이스 연결작업
// 데이터베이스 동기화
models.sequelize
.sync()
.then(()=> {
console.log('DB연결 성공');
})
.catch(e=>{
console.error(e);
console.log('DB연결 에러');
// 서버실행이 안되면 프로세서를 종료
process.exit();
})
})
package.json
{
"name": "lamp-shopping-server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.1",
"multer": "^1.4.5-lts.1",
"sequelize": "^6.21.2",
"sqlite3": "^5.0.8"
}
}
LAMP-SHOPPING-CLIENT
config
config/constansts.js
// export const API_URL = "http://localhost:3000";
export const API_URL = "https://lamp-shopping-server-7ingout.herokuapp.com";
customHook
customHook/useAsync.js
import { useReducer, useEffect, useCallback } from "react"
const initialState = {
loading: false,
data: null,
error: null
}
// 로딩중? 데이터 받기 성공? 데이터 받기 실패
// LOADING , SUCCESS, ERROR
function reducer(state, action){
switch(action.type) {
case "LOADING":
return {
loading: true,
data: null,
error: null
};
case "SUCCESS":
return {
loading: false,
data: action.data,
error: null
}
case "ERROR":
return {
loading: false,
data: null,
error: action.error
}
default:
return state;
}
}
function useAsync(callback, deps=[]) {
const [state, dispatch] = useReducer(reducer, initialState);
const fetchDate = async () => {
dispatch({type: "LOADING"});
try {
const data = await callback();
dispatch({
type: "SUCCESS",
data: data
})
}
catch(e){
dispatch({
type: "ERROR",
error: e
})
}
}
useEffect(()=>{
fetchDate();
// eslint-disable-next-line
}, deps);
return [state, fetchDate];
}
export default useAsync
include
include/Header.js
import React from 'react';
import { NavLink } from 'react-router-dom';
const Header = () => {
return (
<div id="header">
<div className="inner">
<h1><NavLink to ='/'>램프쇼핑</NavLink></h1>
<ul>
{/* <li>상품등록하기</li>
<li>상품보기</li> */}
<li><NavLink to ='/upload'>상품등록하기</NavLink></li>
<li><NavLink to ='/products'>상품보기</NavLink></li>
</ul>
</div>
</div>
);
};
export default Header;
include/Footer.js
import React from 'react';
const Footer = () => {
return (
<div id="footer">
<div id="footer-info">
<div className='inner'>
<div>
<h3>무통장 입금계좌</h3>
<p>BANK ACCOUNT</p>
<p>301-1234-5678-01</p>
<p>예금주 - 김그린(그린조명)</p>
</div>
<div>
<h3>고객센터</h3>
<p>영업시간 이외에는 문의 게시판을 이용해주시면 담당자 확인 후 빠른 답변 도와드리겠습니다.</p>
<p id="tel">02-1263-1245</p>
</div>
<div>
<h3>공지사항</h3>
<ul>
<li>조명가이드 <span>2022-06-20</span></li>
<li>신상품 입고 안내 <span>2022-06-10</span></li>
<li>Mall 오픈을 축하드립니다. <span>2022-02-20</span></li>
</ul>
</div>
</div>
</div>
<div id="footer-copy">
<div className='inner'>
<ul>
<li>홈</li>
<li>그린매장안내</li>
<li>이용약관</li>
<li>개인정보처리방침</li>
</ul>
</div>
<div id="copyright">
<div className='inner'>
상호 : 그린조명 주소 : 울산광역시 남구 삼산중로 100번길
대표전화 : 국번없이 052-1234-4223 대표이사 : 김그린
개인정보관리자 : 이블루 사업자 등록번호 : 102-12-12345
copyright(c) Green Lamp,.LTD all rights reserved.
</div>
</div>
</div>
</div>
);
};
export default Footer;
main
main/index.js
import React from 'react';
import './index.scss';
import axios from 'axios';
// import useAsync from './useAsync';
import useAsync from '../customHook/useAsync';
import MainProduct from './MainProduct';
import { API_URL } from '../config/contansts'
import { Carousel } from 'antd';
// 비동기
async function getProducts() {
const response = await axios.get(`${API_URL}/products`);
return response.data;
}
// carousel
const contentStyle = {
height: '160px',
color: '#fff',
lineHeight: '160px',
textAlign: 'center',
position: 'absolute',
bottom: '50px'
};
const MainPage = (props) => {
// * 쌤 (비동기)
const [state ] = useAsync(getProducts, [])
const { loading, data:products, error} = state;
if(loading) return <div>로딩중 ......</div>
if(error) return <div>에러가 발생했습니다.</div>
if(!products) return <div>로딩중입니다.</div>
// * 김효진 (비동기)
// const [ state ] = useAsync(getProducts);
// const { loading, data:products, error } = state;
// if(loading) return <div>로딩중...</div>
// if(error) return <div>에러가 발생했습니다.</div>
// if(!products) return <div>상품이 없습니다.</div>;
// 원래 받아오던 방법 (비동기 x)
// const [ products, setProducts ] = useState([]);
// useEffect(()=>{
// axios.get("${API_URL}/products")
// .then((result)=>{
// const products = result.data;
// setProducts(products);
// }).catch((e)=>{
// console.log(e);
// })
// }, [])
// if(products === [] ) return <div>로딩중입니다.</div>
// carousel
const onChange = (currentSlide) => {
console.log(currentSlide);
};
return (
<div>
<div id="main">
<div id="banner">
<Carousel afterChange={onChange} autoplay>
<div>
<img src="images/banners/banner1.png" alt="" />
<h3 style={contentStyle}>1</h3>
</div>
<div>
<img src="images/banners/banner1.png" alt="" />
<h3 style={contentStyle}>2</h3>
</div>
<div>
<img src="images/banners/banner1.png" alt="" />
<h3 style={contentStyle}>3</h3>
</div>
</Carousel>
</div>
<div id="product-list" className='inner'>
<h2>그린조명 최신상품</h2>
<div id="product-items">
{/* 나중에 map 이용해서 밑에꺼 8개 뿌려줄거임 */}
{products.map(product => <MainProduct key = {product.id} product={product} />)}
</div>
</div>
</div>
</div>
);
};
export default MainPage;
main/MainProduct.js
import React from 'react';
import { Link } from 'react-router-dom'
const MainProduct = ( {product} ) => {
return (
<div className="product-card">
<Link to={`/product/${product.id}`}>
<div className='product-img'>
<img src={product.imageUrl} alt="" />
</div>
<div className='product-contents'>
<span className='product-name'>{product.name}</span>
<span className='product-price'>{product.price}</span>
<div className='product-seller'>
<img src="images/icons/avatar.png" alt=""/>{product.seller}
</div>
</div>
</Link>
</div>
);
};
export default MainProduct;
main/index.scss
#banner {
img {
width: 100%;
}
}
#product-list {
h2 {
padding: 30px 0;
}
#product-items {
display: flex;
flex-wrap: wrap;
.product-card {
width: 24%;
border: 1px solid #ccc;
border-radius: 16px;
margin-bottom: 16px;
overflow: hidden;
&:not(:nth-child(4n+0)) {
margin-right: 1.3333%;
}
.product-img {
img {
width: 100%;
}
}
.product-contents {
padding: 24px;
span {
display: block;
}
.product-seller {
padding-top: 16px;
display: flex;
align-items: center;
img {
width: 50px;
}
}
}
}
}
}
product
product/index.js
import React from 'react';
import "./product.scss"
import axios from 'axios';
import { useParams } from 'react-router-dom';
import useAsync from '../customHook/useAsync'
import { useNavigate } from 'react-router-dom';
import { API_URL } from '../config/contansts'
async function getProduct(id) {
const response = await axios.get(`${API_URL}/product/${id}`)
return response.data;
}
const ProductPage = (props) => {
const navigate = useNavigate();
// product /1
const { id } = useParams();
const [state] = useAsync(()=>getProduct(id), [id]);
const { loading, data:product, error } = state;
const productDel = () => {
axios.delete(`${API_URL}/product/${id}`)
.then(result=>{
console.log("삭제되었습니다.");
navigate("/");
})
.catch(e=> {
console.log(e);
})
}
if(loading) return <div>로딩중입니다.....</div>
if(error) return <div>에러가 발생했습니다.</div>
if(!product) return null;
// useEffect(비동기 x)
// const [ product, setProduct ] = useState(null);
// // useParams() 실행되면 파라미터 값을 가지고 있는 객체를 반환
// // product/1
// const { id } = useParams();
// // useEffect(function(){
// // axios.get(`http://localhost:3000/product/${id}`)
// // .then(result=> {
// // console.log(result);
// // const data = result.data;
// // setProduct(data);
// // })
// // .catch(e=> {
// // console.log(e);
// // })
// // }, []) // 빈 배열 넣어줘야 마운트 될 때 한번만 시행
// // if(!product) return <div>로딩중입니다...</div>
return (
<div className='inner'>
<div id="image-box">
<img src={product.imageUrl} alt =""/>
</div>
<div id="profile-box">
<ul>
<li>
<div>
<img src="/images/icons/avatar.png" alt=""/>
<span>{product.seller}</span>
</div>
</li>
<li>
{product.name}
</li>
<li>
가격 {product.price}
</li>
<li>등록일</li>
<li>상세설명</li>
<li>{product.description}</li>
</ul>
</div>
<div>
<span onClick={productDel}>삭제하기</span>
</div>
</div>
);
};
export default ProductPage;
product/product.scss
#image-box {
padding-top: 50px;
display: flex;
align-items: center;
justify-content: center;
img {
width: 50%;
border-radius: 50%;
}
}
#profile-box {
padding: 16px;
margin-top: 10px;
li {
border-bottom: 1px solid #ccc;
line-height: 40px;
div {
display: flex;
align-items: center;
img {
width: 70px;
}
}
}
}
upload
upload/index.js
import React, { useState } from 'react';
import './upload.scss';
import 'antd/dist/antd.css';
import { Form, Divider, Input, InputNumber, Button, Upload } from 'antd';
// import useAsync from '../customHook/useAsync'
import axios from "axios";
import { useNavigate } from 'react-router-dom';
import { API_URL } from '../config/contansts'
// async function postProduct(values){
// const response = await axios.post(`${API_URL}/products`, {
// name: values.name,
// seller: values.seller,
// price: values.price,
// imageUrl: imageUrl // 상태관리 되고 있는 imageurl
// });
// return response.data;
// }
const Uploadpage = (props) => {
const navigate = useNavigate();
// 이미지 경로 상태관리 추가
const [imageUrl, setImageUrl ] = useState(null);
// 이미지 처리함수
const onChangeImage = (info) => {
// 파일이 업로드 중일 때
console.log(info.file)
if(info.file.status === "uploading"){
return;
}
// 파일이 업로드 완료 되었을 때
if(info.file.status === "done") {
const response = info.file.response;
const imageUrl = response.imageUrl;
// 받은 이미지경로를 imageUrl에 넣어줌
setImageUrl(imageUrl);
}
}
const onSubmit = (values) => {
// 서버로 데이터 전송하기
axios.post(`${API_URL}/products`, {
name: values.name,
seller: values.seller,
price: values.price,
imageUrl: imageUrl,
description: values.description
}).then((result)=>{
console.log(result)
navigate("/");
})
.catch(e=>{
console.log(e);
})
}
return (
<div id="upload-container" className='inner'>
<Form name="productUpload" onFinish={onSubmit}>
<Form.Item name="imgUpload"
label={<div className='upload-label'>상품사진</div>}>
<Upload name="image" action={`${API_URL}/image`}
listType="picture" showUploadList={false} onChange={onChangeImage}>
{/* 업로드 이미지가 있으면 이미지를 나타내고 업로드 이미지가 없으면
회색배경에 업로드 아이콘이 나타나도록 ... */}
{ imageUrl ? <img src={imageUrl}
alt="" width= "200px" height= "200px" /> :
(<div id="upload-img-placeholder">
<img src="images/icons/camera.png" alt="" />
<span>이미지를 업로드 해주세요.</span>
</div>)}
</Upload>
</Form.Item>
<Divider/>
<Form.Item name="seller"
label={<div className='upload-label'>판매자명</div>}>
<Input className="nameUpload" size='large'
placeholder='판매자 이름을 입력하세요'/>
</Form.Item>
<Divider/>
<Form.Item name="name"
label={<div className='upload-label'>상품이름</div>}>
<Input
className='upload-name'
size='large'
placeholder='상품 이름을 입력해주세요'/>
</Form.Item>
<Divider/>
<Form.Item name="price"
label={<div className='upload-label'>상품가격</div>}>
<InputNumber defaultValue={0} size="large"/>
</Form.Item>
<Divider/>
<Form.Item name="description"
label={<div className='upload-label'>상품소개</div>}>
<Input.TextArea
size='large'
id = "product-description"
maxLength={300}
placeholder="상품 소개를 적어주세요"
/>
</Form.Item>
<Form.Item>
<Button id="submit-button" size="large" htmlType='submit'>
상품등록하기
</Button>
</Form.Item>
</Form>
</div>
);
};
export default Uploadpage;
upload/upload.scss
#upload-img-placeholder {
width: 200px;
height: 200px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
border: 1px solid rgb(230, 230, 230);
background: rgb(250, 250, 253);
margin-left: 16px;
}
#upload-img-placeholder > img {
width: 50px;
height: 50px;
}
#upload-img-placeholder > span {
font-size: 14px;
color: rgb(195, 194, 204);
}
.upload-label {
width: 100px;
font-size: 18px;
text-align: left;
}
App.js
import './App.css';
import Footer from './include/Footer';
import Header from './include/Header';
import MainPage from './main';
import ProductPage from './product';
import { Routes, Route } from 'react-router-dom';
import Uploadpage from './upload';
function App() {
return (
<div className="App">
{/* 파일이름으로 부르는 것이 아니라 component 이름을 부르기 */}
<Header/>
<Routes>
<Route path="/" element={<MainPage/>}/>
<Route path="/product/:id" element={<ProductPage/>}/>
<Route path="/upload" element={<Uploadpage/>}/>
</Routes>
<Footer/>
</div>
);
}
export default App;
App.css
* { margin: 0; padding: 0; box-sizing: border-box; }
li { list-style: none ;}
a { text-decoration: none; color: inherit; }
body {
font-family: "나눔고딕", sans-serif;
font-size: 16px;
line-height: 1.6;
color: #222;
}
input, section, textarea {
outline: none;
}
table { border-collapse: collapse;}
#header {
height: 64px;
}
.inner {
width: 1200px;
margin: 0 auto;
}
#header .inner {
display: flex;
justify-content: space-between;
align-items: center;
}
#header ul {
display: flex;
}
#header ul li {
padding: 0 10px;
}
#footer {
padding-top: 50px;
}
#footer-info {
border-top: 3px solid #333;
border-bottom: 1px solid #333;
padding-bottom: 20px;
}
#footer-info > div {
display: flex;
justify-content: space-between;
}
#footer-info > div div {
width: 32%;
line-height: 2;
}
#footer-info > div div h3 {
border-bottom: 1px solid #ccc;
padding-top: 20px;
padding-bottom: 10px;
margin-bottom: 20px;
}
#footer-info > div div li {
border-bottom: 1px dotted #ccc;
}
#copyright {
background-color: #eee;
padding: 30px;
border-top: 1px solid #ccc;
}
#footer-copy ul {
display: flex;
padding: 16px 0;
}
#footer-copy ul li {
padding: 0 30px;
line-height: 1;
}
#footer-copy ul li:not(:last-child) {
border-right: 1px solid #ccc;
}
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();