티스토리 뷰

반응형

Nodejs환경에서 express와 mongodb를 활용하여 백엔드 프로젝트를 만들어 보겠다. 아래의 내용을 따라 적기만 하면 몸고db 연결이 될것이다. 시작해보자! 만약 프로젝트에 관한 전반적인 지식이나 frontend와 backend를 동시에 만들고 있다면, 아래의 링크인 nodejs 총 정리를 참고하면 많은 도움이 될것이다.

 

[Web/nodejs] - nodejs 기초 총 정리

> frontend, backend를 포함한 nodejs 총 정리

 

 

 

VScode를 활용하여 기본 셋팅을 준비한다.

 

아무것도 없는 환경에서 시작해 보겠다.

 

설치

 

위와 같이 yarn 설치를 했고 필요한 설치들을 했다. 아래와 같이 순차적으로 인스톨을 해준다.

npm i yarn -g  
yarn add express cors mongoose dotenv @hapi/joi bcrypt
yarn global add nodemon
npm install express-generator -g

 

사실 위와 같이 하나씩 설치하지말고 아래의 내용을 package.json에 복사를 하자.

{
  "name": "soccer-express",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "axios": "^0.24.0",
    "bcrypt": "^5.0.1",
    "bcryptjs": "^2.4.3",
    "body-parser": "^1.20.0",
    "cookie-parser": "^1.4.6",
    "cors": "^2.8.5",
    "debug": "~2.6.9",
    "dotenv": "^16.0.0",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "jade": "~1.11.0",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^6.2.9",
    "morgan": "^1.10.0",
    "next": "^12.1.2",
    "nodemon": "^2.0.15",
    "passport": "^0.5.2",
    "passport-jwt": "^4.0.0",
    "passport-local": "^1.0.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "winston": "^3.7.2"
  },
  "type": "module"
}

 

그 후에 $ npm i 로 설치해 주면된다.

 

파일 구조 생성

생성해야할 파일들은 아래와 같다.

코드를 넣어야 할 부분은 server.js이다. 그리고 app/routes/index.js에는 서버가 잘 돌아가나 테스트 용으로 작성하는 것이다.

 

server.js

코드의 진입점이자 시작점으로 아래와 같이 코드를 넣어준다.

import dotenv from 'dotenv'
import express from 'express'
import morgan from 'morgan'

import index from "./app/routes/index.js"

async function startServer(){
    const app = express()
    
    app.use(express.static('public'));
    app.use(express.urlencoded({extended: true}));
    app.use(express.json());
    app.use("/", index);
    app.use(morgan('dev'))

    app.listen(5000, () => {
        console.log('***************** ***************** *****************')
        console.log('********** 서버가 정상적으로 실행되고 있습니다 *********')
        console.log('***************** ***************** *****************')
    })
}
startServer()

 

 

그리고 index.js에 아래의 코드를 넣어준다.

import express from "express"
const indexRouter = express.Router();

indexRouter.route('/').get(function(_req, res) {
  res.json({"현재 시간 : ": new Date().toLocaleString()})
});

export default indexRouter;

 

이제 서버를 실행해 보자. package.json이 있는 위치에서 아래와 같이 명령어를 처준다. node server.js

 

위와 같은 화면이 뜬다면 서버가 정상적으로 실행되고 있는것이다.

 

위에서 적은 index.js를 확인하기 위해  http://localhost:5000/ 에 접속해 보자.

 

위와 같이 현재 시간이 잘 뜬다면 서버연결은 끝난것이다. 사실 서버를 연결하는 과정은 굉장히 쉽다고 할 수 있다. 조금 더 만들어보자.

 


 

몽고 DB 연결

기본적으로 몽고DB는 설치 되어 있다고 가정하고 진행하겠다. 필자의 경우는 도커로 설치를 하였고 MongoDB compass를 활용하여 데이터 확인을 할 예정이다.

 

우선은 .env 파일을 만들어서 아래와 같이 넣어준다.

 

코드에 숨기고 싶은 다른 값들(AWS key 등등)도 필요시 추가로 넣어 주면 된다.

 

아래와 같이 dotenv를 사용하기 위한 applyDotenv.js로 헬퍼함수를 작성해준다.

 

const applyDotenv = dotenv => {
    dotenv.config()
    return {
        mongoUri : process.env.MONGO_URI,
        port : process.env.PORT,
        jwtSecret : process.env.JWT_SECERT,
        origin : process.env.ORIGIN
    }
}
export default applyDotenv

 

 

DB와 연결하기 위해 app/models/index.js에 아래와 같이 로직을 만들어 준다.

 

 

import dotenv from 'dotenv'
import mongoose from 'mongoose'

mongoose.Promise = global.Promise

const db = {}
db.mongoose = mongoose
db.url = dotenv.MONGO_URI   
// db.User = new UserModel(mongoose)

export default db

 

 

이제 작성한 models와 lambdas를 server.js에서 연결을 해주면 된다. server.js를 아래와 같이 추가해 주자.

 

 

import express from 'express'
import morgan from 'morgan'
import dotenv from 'dotenv'

import index from "./app/routes/index.js"

import db from './app/models/index.js'

import applyDotenv from './app/lambdas/applyDotenv.js'


async function startServer(){
    const app = express()
    const {mongoUri, port, jwtSecret} = applyDotenv(dotenv)
    app.use(express.static('public'));
    app.use(express.urlencoded({extended: true}));
    app.use(express.json());
    app.use("/", index);
    app.use(morgan('dev'))
    db
    .mongoose
    .connect(mongoUri, {
        useNewUrlParser: true,
        useUnifiedTopology: true
    })
    .then(() => {
        console.log('몽고DB 연결 성공')
    })
    .catch(err => {
        console.log('몽고DB와 연결 실패', err)
        process.exit();
    });

    app.listen(5000, () => {
        console.log('***************** ***************** *****************')
        console.log('********** 서버가 정상적으로 실행되고 있습니다 *********')
        console.log('***************** ***************** *****************')
    })
}
startServer()

 

 

서버를 실행해 보자. 그러면 아래와 같이 찍힌다면, 몽고DB도 연결을 한것이다.

 

 

 

 

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함