React - Server

hanyoko·2023년 6월 23일

REACT

목록 보기
11/15
post-thumbnail

Module Loading ...

es6 문법

export, import

export function hello(){

}	//내보내기
import hello from './hello.js'	//불러오기

Common JS 문법

module.export 내보내기(export)
require('이름') 불러오기 (import)
ex) const hello = require("./hello.js")


JSON

JSON Formater을 이용하면 JSON을 코드 프로그램에서 보는 것과 유사한 스타일로 볼 수 있다.


node.js 요소

브라우저가 아닌 곳에서도 js를 실행할 수 있도록 나온 어플리케이션

  1. 설정하고자 하는 이름의 폴더 생성
  2. 터미널에 npm init → npm 패키지 초기화
  3. node 파일 이름 → 자바스크립트 파일 실행
  4. node 환경에서 채택된 자바스크립트 문법은 es6가 아닌 Common JS임.

require(경로)

  • 경로에서 내부 모듈을 가져온다.

createServer((req,res)=>{})

  • 서버 객체를 생성
  • req에는 요청
  • res에는 응답이 담긴다.

서버객체의 method

  • listen() 서버 실행
  • close() 서버 종료
  • writeHead(상태코드, { header 정보 })
  • 헤더 정보를 작성

API 요청 메소드

  • GET : 데이터 조회
  • POST : 데이터 등록
  • PUT : 데이터 수정
  • DELETE : 데이터 제거

axios.get('경로');
axios.post('경로',{데이터});
axios.put('경로', {데이터} ,config]);
axios.delete('경로');


Axios

Axiosnode.js와 브라우저를 위한 Promise 기반 HTTP 클라이언트이다.

  • 그것은 동형이다.(동일한 코드베이스로 브라우저와 node.js에서 실행할 수 있다).
  • 서버 사이드에서는 네이티브 node.jshttp 모듈을 사용하고, 클라이언트(브라우저)에서는 XMLHttpRequests를 사용한다.

axios 설치 방법

npm install axios

axios 사용법

import axios from 'axios';

axios.get('/users/1')
axios.post('경로', { username: "green", id: "aa" })

서버 작성법

1. 터미널 설치

서버 폴더의 터미널에서 아래와 같이 작성하여 jsonmodules등을 설치한다.

  • npm init 지정
  • npm install express 설치
  • npm install cors 설치

npm install mysql 설치

express 서버에서 mysql 연동

1. mysql 설치
2. create database shopping
3. create table products()
4. insert문으로 데이터 생성
5. express 서버에 mysql 설치
npm install mysql
6. mysql 라이브러리 불러오기 const mysql = require("mysql")
7. mysql 접속 생성
8. mysql.createConnection({
host: "localhost",
user: "root",
pasword: "1234",
database: "shopping",
port: "3306"
})
9. mysql 접속 conn.connect()
10. 쿼리 전송 conn.query("쿼리문",(err, result, filed)=>{
//처리할 코드
})
app.get('/products', (req, res)=>{
conn.query("쿼리문",(err, result, filed)=>{
res.send(result)
})
})

2. index.js에 기본 구문 작성

// express server 만들기
const express = require("express");
const cors = require("cors");
const mysql = require('mysql');

// server 생성
const app = express();
//프로세서의 주소 포트번호 지정
const port = 8080;
//브라우저의 CORS 이슈를 막기 위해 사용
app.use(cors());
//json 형식의 데이터를 처리하도록 설정
app.use(express.json());


// mysql 연결 생성
const conn = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "1234",
    port: "3306",
    database: "sample"
})
// 선 연결
conn.connect();

데이터베이스 "localhost"와 연결된 서버가 생성되었다.


3. 데이터 및 요청을 받았을 때의 구문 작성

1) app 서버에 데이터베이스의 데이터 출력하기

//posts 배열을 전송한다.
// req에는 요청정보가 담긴다.
// res에는 응답정보가 담긴다.
app.get("/special",(req,res)=>{
	conn.query("select * from event where e_category = 'special'",
	(error,result,fields)=>{
    	res.send(result)
    })
})
// localhost:8080/special/1 이라면
// req = {params:{no:1}}
app.get("/special/:no",(req,res)=>{
	 const {no}= req.params;
	 conn.query(`select * from event where e_category= 'special' and e_no=${no}`,
	 (error,result,fields)=>{
		res.send(result)
	 })
})

2) app 서버를 통해 데이터베이스에 데이터 넣기

	const addMember=()=>{
		axios.post(`${API_URL}/join`,formData)
		.then(res=>{
			console.log('등록되었습니다.')
		})
		.catch(e=>{
			console.log(e);
		})
	}
    return(
      <form onSubmit={addMember}>
    )
app.post("/join", async (req, res)=>{
	const {m_name}= req.body;
	conn.query(`insert into member(m_name) values('${m_name}')`,
	(err,result,fields)=>{
		result&&res.send("등록되었습니다."); //result가 true일때만 res.send 반환
	})
})

3) app 서버를 통해 데이터베이스의 데이터 수정하기

const onupdate=(id)=>{
	axios.patch(`${serveraddress}addaccounttitle/${id}`,formdata)
	.then(res=>{
		alert("수정되었습니다.")
		window.location.reload()
	})
	.catch(e=>console.log(e))
}

return(
	data.map(d=><button onClick={()=>onupdate(d.id)}>M</button>)
)
app.patch('/addaccounttitle/:id',(req,res)=>{
	const {id} = req.params;
	const {text, fixed} = req.body;
	conn.query(`update titletable set \`desc\`='${text}',
				isFixed='${fixed}' where id='${id}'`
      ,(error, result, fields) => {
		res.send(result);
	})
})

4) app서버의 기본주소(port)에서 listen요청을 받았을 시

// 터미널에 '서버가 동작하고 있습니다.'을 출력한다.
app.listen(port, ()=>{
    console.log("서버가 동작하고 있습니다.");
})

오류 확인

  • errno : 1045
    mysql.createConnection() 내의 작성 오류
  • errno : -4091
    한 서버를 중복으로 돌림 (한개만 돌리면 해결)
  • err 발생 X, 출력 X
    sql문 작성 오류 등
  • 명령어 작성
    sql문 의 테이블명 혹은 컬럼명으로 desc 와 같은 명령어가 지정된다.
    → 백틱[``]으로 감싸면 해결된다
    테이블명과 컬럼명의 이름이 같다
    sql문 내에서 valuesvalues()로 주고 sql, [값 지정], callback() 의 값 지정에서 값을 지정

Postman

서버 테스트 할 수 있는 프로그램

Download Postman
https://www.postman.com/downloads/

0개의 댓글