MYSQL로 DB 만들고 서버 연동

My P·2023년 4월 8일
0
  1. MYSQL 설치 (MySQL Workbench)

  2. 대충 블로그 따라서 DB생성

  3. EXPRESS 웹서버에 연동하려 NPM 설치

  4. 대충 뭐 config파일에 DB정보 입력해서 연결하는거 같음
    유저 등록해야된다고 해서 서버연동까진 안함 귀찮

이 이후는 https://1-day-1-coding.tistory.com/51 해당 페이지 가서 확인하자.

대충 요약하자면

ㄱ.구축 방법

ㄱ-1. Express 웹 서버 실행.
ㄱ-2. MySQL 데이터베이스 Configuration 추가.
ㄱ-3. 'Customer'라는 샘플 모델 생성 후 컨트롤러 작성.
ㄱ-4. CRUD 작업을 처리하기 위한 routes를 정의:

Methods 		Urls				Actions
GET	    		/customers			모든 Customers 조회
GET	    		/customers/:id		id 로 Customers 조회
POST			/customers			Customers 생성
PUT			    /customers/:id		id로 Customers 수정
DELETE			/customers/:id		id로 Customers 삭제
DELETE			/customers			모든 Customer 삭제

ㄱ-5. Postman을 사용해서 Restful API 테스트

ㄴ.Node.js 프로젝트 폴더 생성 및 환경 세팅

ㄴ-1.$ cd nodejs-express-mysql
ㄴ-2.

$ npm init

package name: (nodejs-express-mysql) 
version: (1.0.0) 
description: Node.js Restful CRUD API with Node.js, Express and MySQL
entry point: (index.js) server.js
test command: 
git repository: 
keywords: nodejs, express, mysql, restapi
author: noohk329
license: (ISC) 

Is this OK? (yes) yes

ㄴ-3.

Express, mysql, body-parser 모듈을 설치한다.
$ npm install express mysql body-parser --save

ㄴ-4. 환경 세팅을 마친 후 package.json 파일은 다음과 같이 생성이 되어있다.

{
  "name": "nodejs-express-mysql",
  "version": "1.0.0",
  "description": "Node.js Restful CRUD API with Node.js, Express and MySQL",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "nodejs",
    "express",
    "mysql",
    "restapi"
  ],
  "author": "noohk329",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "mysql": "^2.18.1"
  }
}

ㄷ.Express 웹 서버 세팅

ㄷ-1.root floder 에 server.js 파일을 생성하고 다음과 같이 작성한다.

const express = require("express");
const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.get("/", (req, res)=>{
    res.json({message: "Hello World!"});
});

// 포트넘버 설정
app.listen(3000, ()=>{
    console.log("Server is running on port 3000.");
})

ㄷ-2. Express, bodyParser 모듈 import. (Express: Restapi 구축을 위한 프레임워크 / Body-parser: request를 분석하고, routes에 엑세스 해야 하는 req.body 개체를 만들기 위해 사용)

ㄷ-3 express app을 만든다음 app.use()를 사용해서 body-parser 미들웨어 추가
ㄷ-4 테스트 하기 쉽게 간단한 get 경로 정의
ㄷ-5 포트 3000에서 request 요청 수신
ㄷ-6 VS code 터미널에서 다음 명령어를 입력해서 실행한다.

$ node server.js

ㄷ-7. 웹 브라우저에서 http://localhost:3000/ 에 접속하면 정상적으로 실행되는 것을 볼 수 있다.

ㄹ. MySQL configuration 작성 및 연동

ㄷ-1. app/config 폴더를 생성하고 db.config.js 파일을 생성한다. 파일에는 다음과 같이 작성한다. user-계정, password-설정한 비밀번호, DB-스키마

module.exports = {
    HOST: "localhost",
    USER: "root",
    PASSWORD: "123456",
    DB: "new_db"
};

ㄷ-2. configuration 파일으로 mysql과 연동하는 부분을 작성할 차례!
app/models 폴더 생성 후 db.js 파일을 생성한다.

ㅁ.Routes 정의

ㅁ-1.HTTP 요청(GET, POST, PUT, DELETE)을 받았을 때 어떻게 응답할지 route 정의하는 것!

/customers: GET, POST, DELETE
/customers/:customerID: GET, PUT, DELETE

ㅁ-2. app/routes 폴더 생성하고 customer.routes.js 파일을 작성한다.

module.exports = app =>{
    const customers = require("../controllers/customer.controller.js");

    // 튜플 생성
    app.post("/customers", customers.create);

    // 전체 조회 
    app.get("/customers", customers.findAll);

    // id로 조회
    app.get("/customers/:customerId", customers.findOne);

    // id로 수정
    app.put("/customers/:customerId", customers.update);

    // id로 삭제
    app.delete("/customers/:customerId", customers.delete);

    // 전체 삭제
    app.delete("/customers", customers.deleteAll);

};

ㅂ. Controller 생성

ㅂ-1. app/controller 폴더를 생성하고 customer.controller.js 파일을 작성한다. 컨트롤레 안에 CRUD function을 구현할 것임.

뭐 대충 컨트롤러 안에 CRUD function 구현하는거래 

ㅅ. 그 다음 뭐 서버 돌아가는지 테스트하고 포스트맨 사용해서 API 작동되는지 테스트하래

내가 이해한바는 대충 뭐 DB엔 테이블 형식으로 데이터를 만들어 저장한다.
그리고 노드든 AWS든 뭐든 서버 구성하고 킨다음 만들어놓은 DB 연동한다.
그리고 뭐 컨트롤런지 뭔지에다 DB에 저장된 데이터 CRUD 할 수 있게 CURD function 만든다.
그럼 만드는건 다 끝나는거 같다.
이제 그 만든게 잘 돌아가는지 테스트 하고 끝인거 같다.
대충 뭐 백단에서 데이터가 어케 돌아가고 만들어지고 쓰는지 대충 알게된거 같다.
DB는 여기까지.끝

profile
박문

0개의 댓글