본문 바로가기
Web/Node.js

[인프런] Node JS #1 ~ #7

by jionee 2020. 7. 29.
SMALL

#1 소개

보일러 플레이트(boilerplate)란 ? 

웹사이트를 만들때 자주 쓰이는 기능을 재사용할 수 있도록 만들어 놓은 것

ex) 로그인, 사인업 등

 

#2 Node.JS와 Express.JS 다운로드

Node.JS 란?

자바스크립트를 브라우저(크롬,IE 등)가 아닌 서버 사이드에서 쓸 수 있게 한 프로그래밍 언어

 

Express.JS 란?

Node.JS를 쉽게 이용할 수 있게 해주는 프레임워크

 

Node.JS 설치하기

https://nodejs.org/ko/

 

Node.js

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

nodejs.org

터미널창에 node -v 입력해서 버전이 나오면 설치 완료

 

NPM

Node.JS 기반의 모듈을 모아둔 집합 저장소

Node Package Manager 또는 Node Package Modules라고도 한다.

 

npm init 명령어

$ npm init

pakage.json 파일을 생성함

 

index.js

백엔드 시작점

 

Express.js 다운로드

$ npm install express --save

--save를 입력하면 pakage.json에 express가 함께 표시됨

(다른사람이 봐도 express 라이브러리 사용함을 알 수 있음)

 

https://expressjs.com/ko/starter/hello-world.html

 

Express "Hello World" 예제

Hello world 예제 기본적으로 이 앱은 여러분이 작성할 수 있는 가장 간단한 Express 앱일 것입니다. 이 앱은 하나의 파일로 된 앱이며 Express 생성기를 통해 얻게 되는 앱과는 같지 않습니다. (이 예제�

expressjs.com

참고하여 간단한 Express.js 앱 만들기 (Hello world)

 

앱은 서버를 시작하며 3000번 포트에서 연결을 청취합니다. 앱은 루트 URL( / ) 또는  라우트 에 대한 요청에 “난 지원이”로 응답합니다. 다른 모든 경로에 대해서는  404 Not Found 로 응답합니다.
실행 화면

 

#3 몽고 DB 연결

몽고 DB란 ?

Json 타입의 Document 방식의NoSQL(Non Relational Operation Database SQL) 

대용량 데이터를 처리할 수 있는 관계형 데이터베이스가 아닌 SQL

자바스크립트 문법을 사용하느 오픈소스 데이터베이스

 

몽고 DB 클러스터 만들기

https://cloud.mongodb.com/v2/5f2b086daa6c851d86c7b9fd#clusters/edit?filter=starter

 

Cloud: MongoDB Cloud

 

account.mongodb.com

1. 클라우드 선택 (AWS, 구글 클라우드 플랫폼, Azure)

2. 가장 가까운 국가 선택

3. 클러스트 티어 선택 - M0 Sandbox 선택 ( Free )

4. 클러스트 네임 설정 

 

몽고 DB 유저 생성

 

CONNECT 클릭
* 유저네임과 패스워드는 기억해야함 *

 

IP 화이트리스트 설정 (보안을 위해 아무 IP에서나 접근할 수 없게함)

 

Connect your application 선택
커넥션 스트링 카피해두기 (초록색 부분엔 실제 password,dbname 쓰기)

 

Mongoose란 ?

MongoDB ODM 중 가장 유명

* ODM(Object Document Mapping) : 객체와 문서를 1:1 매칭 즉, 문서를 DB에서 조회할때마다 자바스크립트 객체로 바꿔주는 역할

 

Mongoose 설치

$ npm install mongoose --save

--save를 입력하면 pakage.json에 mongoose가 함께 표시됨

(다른사람이 봐도 mongoose 라이브러리 사용함을 알 수 있음)

 

Node.js 앱에 Mongo DB 연결하기

// index.js

const mongoose = require('mongoose')

mongoose.connect('mongodb+srv://jione:<password>@jione.2qflm.mongodb.net/test?retryWrites=true&w=majority', {
    useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false // 에러방지
}).then(()=>console.log('MogoDB Connected...')) // 연결되면 콘솔창에 'MogoDB Connected...'
.catch(err => console.log(err)) // 연결 안되면 err 보이기
npm run start

#4 Mongo DB Model & Schema

Model 이란 ?

Schema를 감싸 주는 역할

 

Schema 란?

데이터베이스의 구조와 제약조건에 관해 전반적인 명세를 기술한 것

 

Mongoose 모듈로 User 스키마&모델 만들기

// User.js

const mongoose = require('mongoose') //몽구스 모듈 가져오기

const userSchema = mongoose.Schema({ // 스키마 생성
    name: {
        type: String, // 데이터 타입
        maxlength: 50 // 최대 길이
    },
    email: {
        type: String,
        trim: true, // 공백 제거
        unique: 1  // 중복 방지
    },
    password: {
        type: String,
        minlength: 5 // 최소 길이
    },
    lastname: {
        type: String,
        maxlength: 50
    },
    role: {
        type: Number,
        default: 0 // 기본 값
    },
    image: String,
    token: {
        type: String
    },
    tokenExp: {
        type: Number
    }

})

const User = mongoose.model('User', userSchema) // 모듈 생성 ('모듈 이름', 스키마이름)

module.exports = {User} // 모델을 다른 파일에서도 쓸 수 있게 exports

#5 GIT 설치

GIT 이란 ?

버전 관리 시스템(VCS, Version Control System)의 한 종류

하나의 중앙 서버가 존재하지만, 여러 클라이언트들은 각자의 컴퓨터 저장소에 중앙 서버의 전체 사본을 가지고 작업을 하는 분산 모델

소스코드를 주고 받을 필요 없이, 같은 파일을 여러 명이 동시에 작업하는 병렬 개발이 가능

 

GIT 설치 확인

$ git --version

 

GIT 설치하기

https://git-scm.com/

 

Git

 

git-scm.com

로컬 디렉토리에 GIT 저장소 만들기

프로젝트의 디렉토리로 이동

$ git init

GIT의 상태 확인

$ git status

 

GIT 상태 다이어그램

Local : 사용하고 있는 컴퓨터 저장소

remote : 원격 저장소

repo : repository의 준말로 저장소를 뜻함

 

GIT 버전관리 무시 목록 설정

1. .gitignore 파일 최상단 디렉토리에 생성

2. 제외할 파일 작성

// .gitignore

node_modules //노드 모듈 폴더 제외

 

.getignore가 정상작동하지 않을 때

$ git rm -r --cached . // 캐시 전부 삭제
$ git add . // 모두 add
$ git commit -m "처음 저장소에 올림" // 메시지와함께 commit

 

#6 SSH를 이용해 GIT HUB 연결

GIT과 GIT HUB

GIT : 자신의 로컬에서 소스코드를 관리할 수 있는 툴

GIT HUB : 코드를 많은 사람들과 공유하고 수정할 수 있게 해주는 클라우드 서비스 

깃은 툴, 깃허브는 깃을 사용하는 서비스

 

GIT HUB 레파지토리 만들기

https://github.com/

 

Build software better, together

GitHub is where people build software. More than 50 million people use GitHub to discover, fork, and contribute to over 100 million projects.

github.com

Local repository와 Remote repository가 안전하게 통신할 방법

우리의 컴퓨터와 GIT HUB가 안전하게 통신할 방법 => SSH(Secure Shell)

SSH : 네트워크 프로토콜 중 하나로 컴퓨터와 컴퓨터가 인터넷과 같은 Public Network를 통해 서로 통신을 할 때 보안적으로 안전하게 통신을 하기 위해 사용하는 프로토콜

* Secure가 붙은 이유는 안전하기 때문 Telnet은 평문으로 데이터를 주고 받기에 중간에서 데이터를 중간에 캐치할 수 있어 보안상 문제가 존재 SSH는 클라이언트와 서버는 암호화되어 있기 때문에 가로채도 데이터를 알 수 없게 된다.

 

SSH가 설정 되어 있는지 확인

$ ls -a ~/.ssh

id_rsa.pub, id_rsa 가 있다면 이미 SSH가 있는것

 

SSH 설정하기

https://docs.github.com/en/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent

 

Generating a new SSH key and adding it to the ssh-agent - GitHub Docs

Generating a new SSH key and adding it to the ssh-agent After you've checked for existing SSH keys, you can generate a new SSH key to use for authentication, then add it to the ssh-agent. Mac Windows Linux All If you don't already have an SSH key, you must

docs.github.com

위 사이트에서 사용하는 운영체제 누르고 순서대로 따라하기

 

새 SSH 키 설정

$ ssh-keygen -t rsa -b 4096 -C "your_email@example.com" // 이메일 부분에는 GitHub 이메일 주소 입력

사용자 키의 암호(Passphrase) 설정도 자동 로그인을 사용하려면 입력하지 않고 엔터를 입력(키 생성될 때 까지)

 

Background에 SSH Agent 켜기

$ eval "$(ssh-agent -s)"

 

SSH Private Key를 SSH Agent에 넣기

$ ssh-add -K ~/.ssh/id_rsa

 

 

SSH Public Key를 GitHub에 연결

https://docs.github.com/en/github/authenticating-to-github/adding-a-new-ssh-key-to-your-github-account

 

Adding a new SSH key to your GitHub account - GitHub Docs

Adding a new SSH key to your GitHub account To configure your GitHub account to use your new (or existing) SSH key, you'll also need to add it to your GitHub account. Mac Windows Linux All Before adding a new SSH key to your GitHub account, you should have

docs.github.com

SSH Public Key 복사하기

$ pbcopy < ~/.ssh/id_rsa.pub //클립보드에 Public Key 복사됨

 

GitHub에 새 SSH Key 추가하기

GitHub 로그인 -> 프로필 사진 -> Settings -> SSH and GPG Keys -> New SSH Key -> Title&Key 작성 -> Add SSH Key

 

Local App과 GitHub 연결하기

만들어 놓은 레파지토리에 들어가서 코드 한줄씩 복사 

전 강좌에서 commit 진행 했으므로 push 진행

 

GitHub에 Push 하기

$ git push origin master // origin 원격 저장소에 master 브랜치를 push

새로고침 시 GitHub에 올라간걸 볼 수 있음

 

#7 BodyParser & PostMan & 회원 가입 기능

Client - Server 통신하는 법

https://opentutorials.org/course/2614/14790

Client : Server에게 정보를 요청하는 역할  Ex) 크롬

Server : 요청받은 정보를 해석해 Client에게 응답해주는 역할

Body : 데이터를 분석(Parse) 해서 req.Body로 출력해주는 것

BodyParser : 요청의 본문을 해석해주는 미들웨어

 

BodyParser 다운받기

$ npm install body-parser --save

 

PostMan 이란?

발한 API를 테스트하고, 테스트 결과를 공유하여 API 개발의 생산성을 높여주는 플랫폼

* API(Application Programming Interface) : 응용 프로그램에서 사용할 수 있도록, 운영 체제나 프로그래밍 언어가 제공하는 기능을 제어할 수 있게 만든 인터페이스 (내가 만든 서비스가 개인 개발자, 기업, 기관이 제공하는 기능, 프로그램을 사용할 수 있게끔 도와주는 중간 매개체)

 

PostMan 다운로드

Client에서 Request를 줘야 하는데 현재 Client가 없으니 PostMan을 이용해서 Request를 보낸다.

https://www.postman.com/

 

Postman | The Collaboration Platform for API Development

Simplify each step of building an API and streamline collaboration so you can create better APIs—faster

www.postman.com

Routing이란 ?

URL(URI) 요청에 따라 어플리케이션이 응답하는 방법을 결정.

app.METHOD(PATH, HANDLER)

 

* METHOD : Http Method(GET, POST, PUT, DELETE, PATCH 등)

* PATH : [경로]

*  HANDLER : [경로 접근 시, 처리 핸들러]

 

Register Route & 회원가입 만들기 

// index.js

const bodyParser = require('body-parser') // require()함수로 body-parser 모듈 가져오기
const {User} = require("./models/User") // exports한 User 모듈 가져오기


app.post('/register', (req, res) => {
    // 회원 가입 할 때 필요한 정보들을 client에서 가져오면
    // 그것들을 데이터 베이스에 넣어준다.

    const user = new User(req.body) // 유저 정보가 requset.body에 들어있음
    
    user.save((err, userInfo) => { // 정보들이 유저 모델에 저장
        if(err) return res.json({ success: false, err })//저장 실패했을 경우
        return res.status(200).json({ //res.status(200)은 성공 상태 코드
            success: true // 저장 성공했을 경우
        })
    })
})

 

JSON 이란?

JavaScript Object Notation (자바 스크립트 객체 표기법)

데이터를 저장하거나 전송할 때 많이 사용되는 경량의 DATA 교환 형식

통신 방법도 프로그래밍 문법도 아닌 단순히 데이터를 표시하는 데이터 포맷

 

PostMan에서 회원가입 Request Test

 

'Web > Node.js' 카테고리의 다른 글

[인프런] Node JS #8 ~ #14  (0) 2020.08.10

댓글