React- DB & React2
-
어제와 비슷하게 주소관리, 상품관리 , 사용자관리 까지 추가해보겠다.
-
DB는 workbench 에서 테이블을 생성해서 관리하고 react로 프론트를 작성함
-
추가된 부분
- 주소관리에서 수정버튼
- 상품관리 전체데이터 표시
- 사용자관리 와 회원등록
1. 주소관리
- DB 주소관리 ```JS var express = require(‘express’); var router = express.Router(); var db = require(‘../db’);
/* 주소리스트 / router.get(‘/list’, function(req, res, next) { var count =0; var page = req.query.page; var start = (page-1) *5; var sql = ‘select count() total from address’; db.get().query(sql, function(err,rows){ count = rows[0].total; var sql =’select * from address order by id desc limit ?,5’; db.get().query(sql, [start], function(err,rows){ res.send({count:count, rows:rows}); }); }); });
//주소등록 router.post(‘/insert’, function(req,res){ var name= req.body.name; var tel=req.body.tel; var address=req.body.address; var sql = ‘insert into address(name,tel,address) values(?,?,?)’; db.get().query(sql, [name,tel,address], function(err,rows){ res.sendStatus(200); }); });
//주소삭제 router.post(‘/delete’, function(req,res){ var id =req.body.id; var sql=’delete from address where id=?’; db.get().query(sql,[id], function(err,rows){ res.sendStatus(200); }); });
//주소정보 router.get(‘/read/:id’, function(req,res){ var id = req.params.id; var sql=’select * from address where id=?’; db.get().query(sql,[id], function(err,rows){ res.send(rows[0]); }) });
//주소수정 router.post(‘/update’, function(req,res){ var id = req.body.id; var name= req.body.name; var tel=req.body.tel; var address= req.body.address; var sql=’update address set name=?,tel=?,address=? where id=?’; db.get().query(sql, [name,tel,address,id], function(err,rows){ res.sendStatus(200); }) })
module.exports = router;
------
- REACT
- Address.js
```js
import React, { useEffect, useState } from 'react'
import axios from 'axios'
import AddressItem from './AddressItem';
import { Link } from 'react-router-dom';
const Address = () => {
const [addresses, setAddresses] = useState('');
const [page, setPage]= useState(1);
const [lastPage, setLastPage] =useState(1);
const callAPI= async() =>{
const res =await axios.get('/address/list?page='+page)
//console.log(JSON.stringify(res.data, null, 2));
setAddresses(res.data.rows);
setLastPage(Math.ceil(res.data.count/5));
}
useEffect (()=> {
callAPI();
}, [page]);
if(!addresses){
return(<h2>데이터 로딩중..</h2>);
}
return (
<div className='Address'>
<h1>주소관리</h1>
<table>
<span className='link'><Link to ="/address/insert"><button className='ad'>주소등록</button></Link></span>
<tr className='title'>
<td width={50}>번호</td>
<td width={100}>이름</td>
<td width={150}>전화</td>
<td width={200}>주소</td>
<td width={50}>삭제</td>
<td width={50}>수정</td>
</tr>
{addresses.map(address=> <AddressItem addr ={address}/>)}
</table>
<div className='pagenation'>
<button className='sbtn' onClick={()=>setPage(page-1)} disabled={page===1 ? true:false}>이전</button>
<span style=> {page}/{lastPage}</span>
<button className='sbtn' onClick={()=>setPage(page+1)} disabled={page===lastPage ? true:false}>다음</button>
</div>
</div>
)
}
export default Address
- AddressInsert.js ```js import React, { useState } from ‘react’ import axios from ‘axios’;
const AddressInsert = () => { const [addr, setAddr] = useState({ name: ‘홍길동’, tel: ‘010-1234-5678’, address: ‘인천 남동구 간석동’ });
const {name, tel, address} =addr;
const onChange = (e) =>{
const newAddr={
...addr,
[e.target.name]: e.target.value
}
setAddr(newAddr);
}
const onSubmit =async(e)=>{
e.preventDefault();
if(!window.confirm('주소를 등록하실래요?')) return;
const res =await axios.post('/address/insert', addr);
if(res.data==='OK'){
alert('주소등록 성공!');
window.location.replace('/address');
}
}
return (
<div className='Address'>
<h1>주소등록</h1>
<form onSubmit={onSubmit}>
<input placeholder='이름' value={name} name="name" onChange={onChange}/>
<input placeholder='전화' value={tel} name="tel" onChange={onChange}/>
<input placeholder='주소' value={address} name="address" onChange={onChange}/>
<div>
<button type="submit">주소등록</button>
<button type="reset">등록취소</button>
</div>
</form>
</div> ) }
export default AddressInsert
- AddressItem.js
```js
import React from 'react'
import axios from 'axios'
import { Link } from 'react-router-dom';
const AddressItem = ({addr}) => {
const {id, name,tel, address} = addr;
const onDelete = async(id)=>{
if(!window.confirm(`${id}을(를) 삭제하실래요?`)) return;
const res=await axios.post('/address/delete', {id:id});
if(res.data === 'OK'){
alert('주소삭제성공!');
window.location.replace('/address');
}
}
return (
<tr>
<td>{id}</td>
<td>{name}</td>
<td>{tel}</td>
<td>{address}</td>
<td><button onClick={()=>onDelete(id)} className='btn'>삭제</button></td>
<td><Link to ={id && `/address/read/${id}`}><button className='btn'>수정</button></Link></td>
</tr>
);
}
export default AddressItem
- AddressRead.js ( 새로 추가된 부분!) ```js import React, {useState, useEffect} from ‘react’ import axios from ‘axios’
const AddressRead = ({match}) => {
const {id} = match.params;
const [addr, setAddr] = useState({
id:0,
name: '',
tel: '',
address: ''
});
const {name, tel, address} =addr;
const callAPI = async() => {
const res= await axios.get('/address/read/'+id);
setAddr(res.data);
}
useEffect(()=>{
callAPI();
}, [id]);
const onChange = (e) =>{
const newAddr={
...addr,
[e.target.name]: e.target.value
}
setAddr(newAddr);
}
const onSubmit =async(e)=>{
e.preventDefault();
if(!window.confirm('주소를 수정하실래요?')) return;
const res = await axios.post('/address/update', addr);
if(res.data === 'OK'){
alert('주소정보수정완료!');
window.location.replace('/address');
}
}
return ( <div> <div className='Address'> <h1>주소정보</h1> <form onSubmit={onSubmit}> <input placeholder=’이름’ value={name} name=”name” onChange={onChange}/> <input placeholder=’전화’ value={tel} name=”tel” onChange={onChange}/> <input placeholder=’주소’ value={address} name=”address” onChange={onChange}/> <div> </div> </form> </div> </div> ) } export default AddressRead

->주소목록

-> 주소등록

-> 새로추가된 read 부분이다. (주소정보)
## 2. 상품관리
- DB
```js
var express = require('express');
var router = express.Router();
var db = require('../db');
/* 상품리스트 */
router.get('/list', function(req, res, next) {
var count =0;
var page = req.query.page;
var start = (page-1) *5;
var sql = 'select count(*) total from product';
db.get().query(sql, function(err,rows){
count = rows[0].total;
var sql='select *,format(price,0) fprice,date_format(regdate,"%Y-%m-%d") date from product order by id desc limit ?,5';
db.get().query(sql, [start], function(err,rows){
res.send({count:count, rows:rows});
})
})
});
module.exports = router;
-
REACT
-
Product.js ```js import axios from ‘axios’; import React, { useEffect, useState } from ‘react’ import ProductItem from ‘./ProductItem’;
const Product = () => { const [page, setPage] =useState(1); const [products, setProducts] = useState(‘’); const [count, setCount] =useState(0); const [lastPage, setLastPage] =useState(1);
const callAPI = async() => {
const res = await axios.get('/product/list?page=' +page);
setProducts(res.data.rows);
setCount(res.data.count);
setLastPage(Math.ceil(res.data.count/5));
}
useEffect(()=> {
callAPI();
},[page]);
if(!products){
return(<h2>데이터 로딩중..</h2>);
}
return ( <div> <h1>상품관리</h1> <div className='tot'>전체데이터 : {count} 건 </div> <table> <tr className='title'> <td width={50}>번호</td> <td width={150}>상품명</td> <td width={150}>가격</td> <td width={150}>판매처</td> <td width={50}>삭제</td> </tr> {products.map(product=> <ProductItem pro = {product}/>)} </table> <div className='pagenation'> <button className=’sbtn’ onClick={()=>setPage(page-1)} disabled={page===1 ? true:false}>이전</button> <span style=> {page}/{lastPage}</span> <button className=’sbtn’ onClick={()=>setPage(page+1)} disabled={page===lastPage ? true:false}>다음</button> </div> </div> ) }
export default Product
- ProductItem.js
```js
import React from 'react'
const ProductItem = ({pro}) => {
const {id, title,fprice, company} = pro;
return (
<tr>
<td>{id}</td>
<td>{title}</td>
<td>{fprice}</td>
<td>{company}</td>
<td><button className='btn'>삭제</button></td>
</tr>
);
}
export default ProductItem
3. 사용자관리
- DB
var express = require('express');
var router = express.Router();
var db =require('../db');
/* 사용자 목록 */
router.get('/list', function(req, res, next) {
var page = req.query.page;
var start = (page-1)*4;
var count =0;
var sql = 'select count(*) count from user';
db.get().query(sql,function(err,rows){
count= rows[0].count;
var sql ='select * from user limit ?,4';
db.get().query(sql, [start], function(err,rows){
res.send({count:count, rows:rows});
})
})
});
/*사용자등록 */
var multer = require('multer');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './public/images')
},
filename: (req, file, cb) => {
cb(null, `${Date.now()}_${file.originalname}`);
}
});
const upload = multer({storage});
router.post('/insert', upload.single('image'), function(req, res){
var id=req.body.id;
var pass=req.body.pass;
var name=req.body.name;
var image='/images/' + req.file.filename;
var sql='insert into user(id,pass,name,image) values(?,?,?,?)';
db.get().query(sql, [id,pass,name,image], function(err, rows){
res.sendStatus(200);
});
});
module.exports = router;
-
REACT
-
User.js ```js import React, { useEffect, useState } from ‘react’ import axios from ‘axios’; import UserItem from ‘./UserItem’; import ‘./User.css’; import { Link } from ‘react-router-dom’;
const User = () => { const [users,setUsers] = useState(‘’); const [page, setPage] = useState(1); const [lastPage, setLastPage] =useState(1);
const callAPI = async() => { const res=await axios.get(‘/users/list?page=’ +page); setUsers(res.data.rows); setLastPage(Math.ceil(res.data.count/4));
}
useEffect(()=>{ callAPI(); },[page]);
if(!users){ return(<h2>데이터 로딩중..</h2>); }
return ( <div> <div className='User'> <h1>사용자관리</h1> <div style=> </Link> </div> {users.map(user =><UserItem user={user}/>)} </div> <div className=''> <button className=’sbtn’ onClick={()=>setPage(page-1)} disabled={page===1 ? true:false}>이전</button> <span style=> {page}/{lastPage}</span> <button className=’sbtn’ onClick={()=>setPage(page+1)} disabled={page===lastPage ? true:false}>다음</button> </div> </div>
) }
export default User
- UserInsert.js
```js
import React, { useState } from 'react'
import axios from 'axios';
const UserInsert = () => {
const [user, setUser] =useState({
id:'',
pass:'',
name:'',
file:null,
fileName:''
})
const {id,pass,name,file,fileName}= user;
const [img, setImg] = useState('http://placeimg.com/300/350/59');
const onFileChange= (e) => { //파일이 변경된경우
var reader = new FileReader();
reader.onload = e=>{setImg(e.target.result)};
reader.readAsDataURL(e.target.files[0]);
const newUser = {
...user,
file:e.target.files[0],
fileName: e.target.value
}
setUser(newUser);
}
const onSubmit = async(e) => {
e.preventDefault();
if(!window.confirm('회원을 등록하실래요?')) return;
const formData = new FormData();
formData.append('image', file);
formData.append('id', id);
formData.append('pass',pass);
formData.append('name', name);
const config={
Headers:{'content-type':'multipart/form-data'}
};
const res= await axios.post('/users/insert', formData, config);
if(res.data==='OK'){
alert('회원등록성공!');
window.location.replace('/user');
}
}
const onChange = (e) => {
const newUser={
...user,
[e.target.name]:e.target.value
}
setUser(newUser);
}
return (
<div>
<h1>회원등록</h1>
<form onSubmit={onSubmit}>
<img src={img} width={500} />
<input type ="file" onChange={onFileChange} accept="image/*"/>
<input placeholder='아이디' name="id" value={id} onChange={onChange}/>
<input placeholder='비밀번호' name="pass" type="password" value={pass} onChange={onChange}/>
<input placeholder='성명' name="name" value={name} onChange={onChange}/>
<div>
<button>회원등록</button>
<button>등록취소</button>
</div>
</form>
</div>
)
}
export default UserInsert
- UserItem.js ```js import React, { useState } from ‘react’ import ‘./User.css’;
const UserItem = ({user}) => { const {id,pass,name,image} = user; return ( <div className='item1'> <img src ={image}/> <div>{name}[{id}]</div> </div> ) }
export default UserItem ```
-> 사용자관리 메인부분(목록)
-> 파일을 선택하면 이미지를 미리보기로 가져온다. 아이디 비번 성명을 입력하면 사용사관리 메인부분에 출력이된다.
댓글남기기