[React] Lamp 쇼핑몰 구현하기 2 (Node.js 서버 만들기)
lamp-shopping-client
lamp-shopping-server
서버 - API 서버
정보를 제공하는 서버
server은 리액트로 설치안하고 그냥 폴더 만든 후 터미널 열고 ~
npm init ~
서버는 웹브라우저로 보지 않고 터미널에 node ~ 치기
test.js
console.log('hello server!!!');
ex> node test.js
react -> es6
node -> Common js
모듈
1. es6 방식
1) 내보내기
export function hello(){
}
function hello(){
}
export default hello;
2) 불러오기
import helo from './hello.js';
2. CommonJS 방식
1) 내보내기 (export)
function hello() {
}
module.exports = hello;
2) 불러오기 (import)
const hello = require('./hello.js')
hello();
http status codes
200 성공
300 redirection
400 client error - 요청하는 쪽 잘못
500 server error
https://expressjs.com/ko/starter/installing.html
Express 설치
설치 Node.js가 이미 설치되었다고 가정한 상태에서, 애플리케이션을 보관할 디렉토리를 작성하고 그 디렉토리를 작업 디렉토리로 설정하십시오. $ mkdir myapp $ cd myapp npm init 명령을 이용하여 애플
expressjs.com
npm install express
npm install cors
https://www.postman.com/downloads/
Download Postman | Get Started for Free
Try Postman for free! Join 20 million developers who rely on Postman, the collaboration platform for API development. Create better APIs—faster.
www.postman.com
index.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('조명쇼핑몰 서버가 돌아가고 있습니다.');
server.js
const express = require("express");
const cors = require("cors");
const app = express();
const port = 3000;
// json형식의 데이터를 처리할 수 있게 설정
app.use(express.json());
// 브라우저 cors 이슈를 막기 위해 사용(모든 브라우저의 요청을 일정하게 받겠다)
app.use(cors());
// 요청처리
// app.메서드(url, 함수)
app.get('/products',async(req,res)=>{
const result = {
products: [
{
id: 1,
name: "거실조명",
price: 50000
},
{
id: 2,
name: "아동조명",
price: 50000
}
]
}
res.send(result);
})
// 실행
app.listen(port, ()=>{
console.log('쇼핑몰 서버가 동작중입니다.');
})
postman
locallhost:3000/products
server 설치 후
main/index.js 가서 {useState, useEffect} import 하기
Mainpage 안에 useEffect 함수 구현, get 방식으로 보냄,
그럼 server.js안에 get 메서드로 구현된 애가 어 나야 나 하면서 안에 있는 상품들(result) 보내줌
key는 products로 사용 (왜냐 server.js에 상품들이 products란 이름안에 구현되었기 때문)
result.data.products 하면 안에 배열만 mainpage 안의 products안에 담김
const products = result.data.products // 이케 변수로 선언해서
setProducts(products); // setProducts 안에 넣기
--- db 설치하기 전이라서 db서부터 안받아오고 server에서 받아옴(원래는 이렇게 안함!!) ---
LAMP-SHOPPING-CLIENT
main/index.js
import React, {useState, useEffect} from 'react';
import './index.scss';
import axios from 'axios';
const MainPage = (props) => {
const [ products, setProducts ] = useState([]);
useEffect(()=>{
axios.get("http://localhost:3000/products")
.then((result)=>{
const products = result.data;
setProducts(products);
}).catch((e)=>{
console.log(e);
})
}, [])
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 => (
<div className="product-card" key={product.id}>
<div className='product-img'>
<img src={product.imgsrc} 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>
</div>
))}
</div>
</div>
</div>
</div>
);
};
export default MainPage;
-------------------------
server에는 .gitigore 파일이 없어서 만들기 (git에 안올릴 파일들을 적어놓는 파일)
node_modules는 원래 안올림