Node 의 최신 버전을 사용하는 것도 좋지만, 안정화 버전 (lts) 를 사용하고 싶고,,, Node 의 버전을 쉽게 관리할 수 있는 n 을 설치해보자.

npm install -g n

 

node version 이 저장되는 디렉토리를 사용자 디렉토리 하위로 변경하였다.

아래 명령어는 tj/n github 에서 확인 가능하다.

export N_PREFIX=/Users/<사용자폴더>/n
export PATH=$N_PREFIX/bin:$PATH

https://github.com/tj/n

 

GitHub - tj/n: Node version management

Node version management. Contribute to tj/n development by creating an account on GitHub.

github.com

 

node 의 버전은 아래와 같이 다운로드 가능하다.

n latest -- 최신버전
n lts -- lts 최신버전

n 명령어로 원하는 node 버전을 선택할 수 있다.

n

Glitch 를 사용해서 간단하게 Node.js를 사용해볼 수 있다.

https://glitch.com

 

Glitch: The friendly community where everyone builds the web

Simple, powerful, free tools to create and use millions of apps.

glitch.com

 

회원가입 후 로그인

 

Node.js 의 'Blank Node' 를 클릭해서 Web 상에서 node 를 사용해보자

 

server.js 를 간단하게 수정해보고,  하단의 Preview 버튼을 클릭하면 작성한 내용이 오른쪽 panel 에 표시된다.

그 외 Log, Terminal, Status 등 확인이 가능하다.

 

node 설치

brew install node

 

node & npm 버전 확인

node -v
npm -v

node & npm 버전 확인

 

yarn 설치

brew install yarn

 

yarn 버전 확인

yarn -v

 

* homebrew 가 아닌 node 또는 yarn 공식 홈페이지에서 설치 가능하다.

mongoose 모듈 설치

% npm install mongoose --save

 

mongoose 모듈 불러오기

var mongoose = requrire('mongoose');

 

mongoDB 연결 셋업

mongoDB는 서버 시작 시 default 로 27017 port 를 사용하고 있으니 참고하자.

 

> 변수 선언

// 데이터베이스 객체를 위한 변수 선언
var database;

// 데이터베이스 스키마 객체를 위한 변수 선언
var UserSchema;

// 데이터베이스 모델 객체를 위한 변수 선언
var UserModel;

> DB 연결 함수

// 데이터베이스에 연결
function connectDB(){
    // 데이터베이스 연결 정보
    var databaseUrl = 'mongodb://localhost:27017/local';

    // 데이터베이스 연결
    console.log('데이터베이스 연결을 시도합니다.');
    mongoose.Promise = global.Promise;
    mongoose.connect(databaseUrl, {useNewUrlParser: true, useUnifiedTopology: true});
    database = mongoose.connection;

    database.on('error', console.error.bind(console, 'mongoose connection error'));
    database.once('open', function(){
        console.log('데이터베이스에 연결되었습니다. : ' + databaseUrl);

        // 스키마 정의
        UserSchema = mongoose.Schema({
            id : String,
            name : String,
            password : String
        });
        console.log('UserSchema 정의함.');

        //UserModel 모델 정의
        UserModel = mongoose.model('users', UserSchema);
        console.log('UserModel 정의함.');
    });

    // 연결 끊어졌을 때 5초 후 재연결
    database.on('disconnected', function(){
        console.log('연결이 끊어졌습니다. 5초 후 다시 연결합니다.');
        setInterval(connectDB, 5000);
    });
    
}

 

mongoose 로 사용자 인증하기

간단하게 Client 에서 id, password 를 전달받은 뒤 DB에 해당 값이 있는 지 확인해보자.

// 사용자 인증하는 함수
var authUser = function(database, id, password, callback) {
    console.log('authUser 호출됨 : ' + id + ', ' + password);

    // 아이디와 비밀번호를 사용해 검색
    UserModel.find({"id" : id, "password" : password}, function(err, results){
        if(err) {
            callback(err, null);
            return;
        }

        console.log('아이디 [%s], 비밀번호 [%s]로 사용자 검색 결과', id, password);
        console.dir(results);

        if(results.length > 0){
            console.log('일치하는 사용자 찾음.', id + ', ' + password);
            callback(null, results);
        } else {
            console.log('일치하는 사용자를 찾지 못함.');
            callback(null, null);
        }
    });
    
};

 

> Client 소스

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>로그인 테스트</title>
    </head>
    <body>
        <h1>로그인</h1>
        <br>
        <form method="post" action="/process/login">
            <table>
                <tr>
                    <td><label>아이디</label></td>
                    <td><input type="text" name="id"></td>
                </tr>
                <tr>
                    <td><label>비밀번호</label></td>
                    <td><input type="password" name="password"></td>
                </tr>
            </table>
            <input type="submit" value="전송" name="">
        </form>
    </body>
</html>

 

> 전송 버튼 클릭 시 호출 Method

authUser 함수가 어떻게 사용되는 지 확인해보자.

// 라우팅 함수 등록
router.route('/process/login').post(function(req,res){
    console.log('/process/login 처리함.');

    var paramId = req.body.id;
    var paramPassword = req.body.password;

    if(database){
        authUser(database, paramId, paramPassword, function(err, docs){
            if(err) {throw err;}

            if(docs){
                console.dir(docs);

                res.writeHead('200', {'Content-Type':'text/html;charset=utf-8'});
                res.write('<h1>로그인 성공</h1>');
                res.write('<div><p>Param id : ' + paramId + '</p></div>');
                res.write('<div><p>Param password : ' + paramPassword + '</p></div>');
                res.write("<br><br><a href='/public/login.html'>다시 로그인하기</a>");
                res.end();

            } else {

                res.writeHead('200', {'Content-Type':'text/html;charset=utf-8'});
                res.write('<h1>로그인 실패</h1>');
                res.write('<div><p>아이디와 비밀번호를 다시 확인하십시오.</p></div>');
                res.write('<div><p>Param password : ' + paramPassword + '</p></div>');
                res.write("<br><br><a href='/public/login.html'>다시 로그인하기</a>");
                res.end();
            }
        })
    } else {
        res.writeHead('200', {'Content-Type':'text/html;charset=utf-8'});
                res.write('<h2>데이터베이스 연결 실패</h2>');
                res.write('<div><p>데이터베이스에 연결하지 못했습니다.</p></div>');
                res.end();
    }
});

몽고디비 서버 시작

 

% brew services start mongodb-community@4.4

==> Successfully started `mongodb-community` (label: homebrew.mxcl.mongodb-community)

 

> use local
switched to db local
> db.users.insert({id:'test006',password:'12345',name:'엠케이'})
WriteResult({ "nInserted" : 1 })
> db.users.find({id:'test006'}).pretty()
{
	"_id" : ObjectId("6076dc9b9e3cedcde7d6e39b"),
	"id" : "test006",
	"password" : "12345",
	"name" : "엠케이"
}
> 

 

몽고디비 서버 중지

 

% brew services stop mongodb-community@4.4

몽고디비란?

  - 비관계형 데이터베이스 : NoSQL or Not Only SQL

 

몽고디비 Mac 초기 설정 (homebrew 사용)

Install Xcode Command-Line Tools

 

   % xcode-select --install

 

Installing MongoDB 4.4 Community Edition

 

   % brew tap mongodb/brew

   % brew install mongodb-community@4.4

 

포함된 사항

파일 및 디렉토리 위치

configuration file

/usr/local/etc/mongod.conf

log directory

/usr/local/var/log/mongodb

data directory

/usr/local/var/mongodb

 

몽고 서버 시작 및 종료 명령어

 

   % brew services start mongodb-community@4.4
   % brew services stop mongodb-community@4.4

 

 

몽고 Shell 접속

 

   % mongo

 

 

 

 

출처 : docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/

+ Recent posts