웹브라우저
API 서버
데이터베이스 - mySQL
1. 데이터베이스 프로그램을 설치
2. 데이터베이스 생성
3. 테이블 생성 (데이터를 논리적으로 나누도록 컬럼을 설정)
4. 테이블에 데이터를 추가한다.
sqlite데이터베이스
- 개발용으로 많이 사용
- ORM(Object Relational Mapping): 서버에서 데이터베이스를 손쉽게 다루도록 도와주는 툴을 의미함
- 데이터베이스 모델링을 쉽게 할 수 있음
- SQL을 사용하지 않고 CRUD 작업을 할 수 있음
LAMP-SHOPPING-SERVER
Sqlite와 Sequelize 사용하기
1.sqlite와 sequelize 설치하기
npm install sequelize sqlite3
2. sequelize 기본환경 설치
npm install -g sequelize-cli
npx sequelize init
3. config.json 요로코롬 수정하기
{
"development": {
"storage": "./database.sqlite3",
"dialect": "sqlite"
},
"test": {
"storage": "memory",
"dialect": "sqlite"
},
"production": {
"storage": "./database.sqlite3",
"dialect": "sqlite"
}
}
4. server.js
const models = require('./models'); 위에 선언 후 밑에 코드 추가하기
// 실행
app.listen(port, ()=>{
console.log('쇼핑몰 서버가 동작중입니다.');
// sequelize와 데이터베이스 연결작업
// 데이터베이스 동기화
models.sequelize
.sync()
.then(()=> {
console.log('DB연결 성공');
})
.catch(e=>{
console.error(e);
console.log('DB연결 에러');
// 서버실행이 안되면 프로세서를 종료
process.exit();
})
})
터미널에 node server.js 실행시키면 성공했다고 뜬다 !
5. 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
},
imgageUrl: {
type: DataTypes.STRING(500),
},
seller: {
type: DataTypes.STRING(200),
allownull: false
},
});
return product;
}
6. DB Browser for SQLite 설치 후 실행
Sqlite 데이터베이스를 GUI환경에서 보여주는 도구
Downloads - DB Browser for SQLite
(Please consider sponsoring us on Patreon 😄) Windows Our latest release (3.12.2) for Windows: Windows PortableApp Note - If for any reason the standard Windows release does not work (e.g. gives an error), try a nightly build (below). Nightly builds ofte
sqlitebrowser.org
데이터베이스 열기 클릭 !
* sqlite 데이터 조회하기
불러오기
const models = require('./models');
1. 조회하기
1) 여러개의 데이터 조회하기
models.Product.findAll()
.then(products=>{
res.send({
products
})
})
2) 하나만 조회하기
models.Product.findOne({
where: {
id:1,
}
})
2. 테이블에 데이터를 넣기(insert)
models.Product.create
models.Product.create({
name: "abc",
price: 50000,
seller: "a",
imageUrl: "/images/###.jpg"
})
.then(result=>{
console.log("상품생성결과", result)
})
.catch(e=>{
console.error(e)
})
7. server.js
// 요청처리
// app.메서드(url, 함수)
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);
});
8. LAMP-SHOPPING-CLIENT
main/index.js 수정 (내가 한 것)
import React, {useState, useEffect} from 'react';
import './index.scss';
import axios from 'axios';
import useAsync from './useAsync';
import MainProduct from './MainProduct';
async function getProducts() {
const response = await axios.get("http://localhost:3000/products");
return response.data;
}
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 [ products, setProducts ] = useState([]);
// useEffect(()=>{
// axios.get("http://localhost:3000/products")
// .then((result)=>{
// const products = result.data;
// setProducts(products);
// }).catch((e)=>{
// console.log(e);
// })
// }, [])
// if(products === [] ) return <div>로딩중입니다.</div>
return (
<div>
<div id="main">
<div id="banner">
{/* 바로 images 하면 public에 있는 images 들어감 */}
<img src="images/banners/banner1.png" alt="" />
</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/useAsync.js (내가 한 것)
import { useReducer, useEffect } from 'react';
const initialState = {
loading: false,
data: null,
error: null
}
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];
}
export default useAsync;
'Stack > React' 카테고리의 다른 글
[React] 상태관리(useState / useReducer) 복습 (0) | 2022.07.04 |
---|---|
[React] npm start 오류(throw err;) 해결하기 (0) | 2022.07.01 |
[React] Lamp 쇼핑몰 구현하기 3 (서버에 연결하기) (0) | 2022.07.01 |
[React] Lamp 쇼핑몰 구현하기 2 (Node.js 서버 만들기) (0) | 2022.06.30 |
[React] Lamp 쇼핑몰 구현하기 1 (0) | 2022.06.29 |