내일배움캠프 TIL (221213): express 서버 만들기, MongDB 설치와 Mongoose 연결 (에러 멈춰...)

Jiumn·2022년 12월 13일
2
post-thumbnail

오늘 한 일

  • 새로운 팀원들과 인사/자기소개/팀명 정하기
  • express 프레임워크로 웹서버 만들기

express.js 프레임워크로 웹 서버 만들기 기본 코드

// express 프레임워크 라이브러리를 가져와서
const express = require('express');
// express로 app 객체를 만들어주고
const app = express();
const port = 3000;

// get 메소드로 api를 실행할 수 있음
app.get('/', (req, res) => {
  res.send('Hello World!');
});

// app 객체를 통해서 express 서버 열어주는 곳
app.listen(port, () => {
  console.log(port, '포트로 서버가 열렸어요!');
});

thunder client로 api 확인해보기

cannot find module 에러

  • vsc 재실행해보니 에러가 사라졌다. 이유가 뭐지?

module 사용하기

module은 하나의 자바스크립트 파일과 같다.
하나의 module을 파일에 작성하고 외부 파일에서 사용해보자.

  1. moudule 안에 함수를 작성해주고
// 함수 정의
function 함수명() {
  return 결과
}

// 함수 내보내기
module.exports = 함수명

module.exports = 함수명을 작성해주면 해당 함수를 외부(다른 파일)로 내보낼(export) 준비가 끝난 것이다.

  1. 해당 함수를 실행시킬 파일에 다음과 같이 함수를 선언해준다.
const 함수명 = require('파일 경로')
  1. console.log(함수)를 작성한 후 터미널에 다음과 같이 입력해준다.
// 파일 경로를 찾고 파일 내부를 확인해본다
cd modules
ls
  • cd(change directory): 해당 파일이 있는 폴더 경로로 이동
  • ls(list): 해당 폴더의 파일 내용 리스트를 확인

그리고 터미널에서 파일을 실행해주면 결과값이 출력된다.

// 터미널에서 파일을 실행한다
node 파일명.js

문제는 module을 사용하는 방법이 위의 한 가지가 아니라는 것이다.
예를 들어 익명함수로 내보내는 경우,

exports.add = function (a, b) {
  return a + b
}

함수를 사용할 때는 해당 함수를 객체 형태로 내보내기 때문에

console.log(함수명.함수명())

위와 같은 형태로 사용을 해줘야 한다.
이 외에도 여러 가지 방법이 있다...

mongoDB 설치하기

mongoDB 설치 안 돼서 2시간 넘게 난리쳤는데 이 영상이 날 살렸다...

[mongoDB 6.0 설치가 안 된다면(필수 시청)]
How to install MongoDB 6.0.1 on Windows 10 || Install MongoDB 6.0.1 & Mongo Shell (2022)

mongoose로 express 서버와 mongoDB 연결하기

const mongoose = require("mongoose")

const connect = () => {
    mongoose
    .connect("mongodb://localhost:27017/spa_mall")
    .catch(err => console.log(err));
};

mongoose.connection.on("error", err => {
    console.error("몽고디비 연결 에러", err);
});

module.exports = connect;

'mongoose 라이브러리를 연결할 때 왜 에러 처리를 이렇게 2중으로 하는 걸까?'라는 의문이 들었다. (익명함수 선언할 때 catch로 예외 처리를 한 다음, 또 한번 mongoose.connection.on 함수로 한번 더 에러 시에 메시지를 보여주고 있다.)

또 다시 구글링의 힘을 빌려...

노드에서는 예외 처리가 정말 중요하다. 예외란 보통 처리하지 못한 에러를 가리킨다. 예외들은 실행중인 노드 프로세스를 멈추게 만든다.
멀티 스레드에서는 스레드 하나가 멈추면 그 일을 다른 스레드가 대신하지만, 노드의 메인 스레드는 하나 뿐이므로 메인스레드가 에러로 인해 멈추면 프로세스 자체가 멈춘다. 즉, 전체 서버가 멈춘다. 따라서 에러 처리 방법은 중요하고, 에러 로그가 기록되더라도 작업은 계속 진행 될 수 있게 해야한다.
출처: nodeJS - 예외 처리하기(try/catch) / 자주 발생하는 에러

그렇다고 한다.

https://stickie.tistory.com/66

문제는 실행 시 에러가 발생하는 것이었는데...

// 에러 발생 시 터미널 메시지
Node.js v18.12.1
PS C:\Users\82102\Desktop\sparta\Node.js_입문주차\spa_mall> node app.js
(node:21616) [MONGOOSE] DeprecationWarning: Mongoose: the `strictQuery` option will be switched back to `false` by default in Mongoose 7. Use `mongoose.set('strictQuery', false);` if you want to prepare for this change. Or use `mongoose.set('strictQuery', true);` to suppress this warning.
(Use `node --trace-deprecation ...` to show where the warning was created)
3000 포트로 서버가 열렸어요!
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
    at Connection.openUri (C:\Users\82102\Desktop\sparta\Node.js_입문주차\spa_mall\node_modules\mongoose\lib\connection.js:825:32)
    at C:\Users\82102\Desktop\sparta\Node.js_입문주차\spa_mall\node_modules\mongoose\lib\index.js:417:10
    at C:\Users\82102\Desktop\sparta\Node.js_입문주차\spa_mall\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
    at new Promise (<anonymous>)
    at promiseOrCallback (C:\Users\82102\Desktop\sparta\Node.js_입문주차\spa_mall\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)  
    at Mongoose._promiseOrCallback (C:\Users\82102\Desktop\sparta\Node.js_입문주차\spa_mall\node_modules\mongoose\lib\index.js:1270:10)
    at Mongoose.connect (C:\Users\82102\Desktop\sparta\Node.js_입문주차\spa_mall\node_modules\mongoose\lib\index.js:416:20)
    at connect (C:\Users\82102\Desktop\sparta\Node.js_입문주차\spa_mall\schemas\index.js:5:6)
    at Object.<anonymous> (C:\Users\82102\Desktop\sparta\Node.js_입문주차\spa_mall\app.js:7:1)
    at Module._compile (node:internal/modules/cjs/loader:1159:14) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined
}
몽고디비 연결 에러 MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
    at Connection.openUri (C:\Users\82102\Desktop\sparta\Node.js_입문주차\spa_mall\node_modules\mongoose\lib\connection.js:825:32)
    at C:\Users\82102\Desktop\sparta\Node.js_입문주차\spa_mall\node_modules\mongoose\lib\index.js:417:10
    at C:\Users\82102\Desktop\sparta\Node.js_입문주차\spa_mall\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
    at new Promise (<anonymous>)
    at promiseOrCallback (C:\Users\82102\Desktop\sparta\Node.js_입문주차\spa_mall\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)  
    at Mongoose._promiseOrCallback (C:\Users\82102\Desktop\sparta\Node.js_입문주차\spa_mall\node_modules\mongoose\lib\index.js:1270:10)
    at Mongoose.connect (C:\Users\82102\Desktop\sparta\Node.js_입문주차\spa_mall\node_modules\mongoose\lib\index.js:416:20)
    at connect (C:\Users\82102\Desktop\sparta\Node.js_입문주차\spa_mall\schemas\index.js:5:6)
    at Object.<anonymous> (C:\Users\82102\Desktop\sparta\Node.js_입문주차\spa_mall\app.js:7:1)
    at Module._compile (node:internal/modules/cjs/loader:1159:14) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined
}

가장 윗 부분을 보니 strictQuery라고 적혀 있어서 이 부분이 잘못되었나 하고...

PS C:\Users\82102\Desktop\sparta\Node.js_입문주차\spa_mall> node app.js
(node:21616) [MONGOOSE] DeprecationWarning: Mongoose: the `strictQuery` option will be switched back to `false` by default in Mongoose 7. Use `mongoose.set('strictQuery', false);` if you want to prepare for this change. Or use `mongoose.set('strictQuery', true);` to suppress this warning.
(Use `node --trace-deprecation ...` to show where the warning was created)

다음 코드를 추가해줬다.

mongoose.set('strictQuery',true)

윗 부분 메시지는 사라졌지만 mongdb와의 연결은 계속 실패했다.

ip 주소가 허용되지 않아서 발생하는 연결 실패라는 말에 mongDB 사이트에서 ip주소 등록도 해보고...

https://www.inflearn.com/questions/29435/%EC%B0%B8%EA%B3%A0-error-mongooseserverselectionerror

그래도 안 되길래 어떤 유튜브 영상을 찾아보니,
다음과 같이 url을 변경하라는 내용이 있었다.

const connect = () => {
    mongoose
    .connect("mongodb://127.0.0.1:27017/spa_mall")
    .catch(err => console.log(err));
};

localhost -> 127.0.0.1
이렇게 변경했더니 에러가 발생하지 않는다.

To-do list

  • MongoDB 연결 해결하기
  • 스파르타 Node.js 입문 강의 완강
  • 개인 과제 시작
profile
Back-End Wep Developer. 꾸준함이 능력이다.

3개의 댓글

comment-user-thumbnail
2022년 12월 15일

와 같은 에러로 혼란했는데 덕분에 잘 해결하고 갑니다! 고맙습니다!

1개의 답글
comment-user-thumbnail
2023년 2월 4일

ㅠㅠㅠㅠㅠㅠㅠㅠㅠ절살리셨어요

답글 달기