API 서버 작성

김수민·2023년 1월 18일
0

React

목록 보기
9/17
export default Hello; //내보내기
import hello from '/hello.js' //불러오기

✔ common.js에서는 위와 같이 쓰던 것을

module.export= Hello; // 내보내기
require("/hello.js") //불러오기

✔ es6에서는 위와 같이 작성한다.


JSON

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

node.js 요소

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

  1. 폴더 생성
  2. npm init npm 패키지 초기화
  3. node 파일명.js JS 파일 실행

require(경로)

경로에서 내부 모듈을 가져옴

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

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

서버객체의 method

  • listen() 서버 실행
  • close() 서버 종료

writeHead(상태코드,{헤더정보})

헤더 정보를 작성

API 요청 메소드

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

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


서버 작성법

1. 터미널 설치

서버 폴더의 터미널에서 아래와 같이 작성하여 json 및 modules등을 설치한다.
1. npm init 지정
2. npm install express 설치
3. npm install cors 설치
4. npm install mysql 설치

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

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

// server 생성
const app= express();
// port 번호 지정
const port= 8080;
// 데이터 전송형식 지정 (JSON)
app.use(express.json());
// cors 이슈 방지
app.use(cors());


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

이제 DB "localhost"와 연결된 서버가 생성되었다.

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

💡app 서버에 DB의 데이터 출력하기

//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)
	 })
})

💡 app 서버를 통해 DB에 데이터 넣기

	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 반환
	})
})

💡 app 서버를 통해 DB의 데이터 수정하기

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);
	})
})

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

// 터미널에 'server is running...'을 출력한다.
app.listen(port,()=>{
  	console.log('server is running...');
})

오류 확인

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

0개의 댓글