<-->
본문 바로가기

프로그래밍/nodeJS

미들웨어 구조와 기본 미들웨어 세팅

반응형

express미들웨어 구조를 사용하는 웹 프레임워크이다.

HTTP 통신 -> 미들웨어 -> NodeJS 실행 순으로 실행된다.

 

 

1. body-parser

 

npm install body-parser

app = express();

app.use(
  express.urlencoded({  //bodyParser을 기반으로한 express버전 구문분석 메소드
    extended: false,
  })
); // 인코딩된 URL 구문 분석

app.use(express.json()); //bodyParser을 기반으로한 express버전 구문분석 메소드

 

2. ejs

 

npm install ejs

app.set("view engine","ejs); //애플리케이션 설정 메소드, view engine을 ejs로 사용한다고 명시해준다

 

3. MongoDB와 자바스크립트 연결

 

mongoose.connect(uri, options) 메소드를 사용한다. 예제에서는 기본세팅만 해보겠다.

mongoose.connect("mongodb://localhost:27017/<db이름>", {useNewUrlParser: true});

ref: docs.mongodb.com/manual/reference/connection-string/

문자열 안의 내용 설명

 

Connection String URI Format — MongoDB Manual

The following provide example URI strings for common connection targets. UNIX Domain Socket Use a URL encoded connection string when connecting to a UNIX domain socket. The following connects to a UNIX domain socket with file path /tmp/mongodb-27017.sock:

docs.mongodb.com

 

4. routers 

 

const router = express.Router();
app.use(router);

 

위 과정이 번거로우면 express-generator가 귀찮음을 해결해 줄수있다!!

 

5. 기본 미들웨어와 MVC 구조를 만들어주는 패키지 -> express-generator

 

npm install express-generator -g

expressjs.com/ko/starter/generator.html

 

Express 애플리케이션 생성기

Express 애플리케이션 생성기 애플리케이션의 골격을 신속하게 작성하려면 애플리케이션 생성기 도구인 express를 사용하십시오. 다음의 명령을 이용해 express를 설치하십시오. $ npm install express-gener

expressjs.com