본문 바로가기
BACK-END

[node.js]서버 구축하기 Express

by 지에스정 2020. 5. 22.

Express 는 Node.js의 프레임워크의 일종으로 간편하게 웹서버를 구축할 수 있다.

 

우선 Express를 설치해보자.

 

$ npm install express --save

 

Express로 서버생성을 하기 위해서 다음과 같이 구성하면 된다.

 

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))

 

그리고 Router로 request를 처리해주면 

 

http://localhost:3000에 접속하였을때 위에서 작성한 Hello World!라는 문구가 나오게 된다.

 

middleware function는 요청 오브젝트(req)와 응답 오브젝트(res), 요청-응답 주기 중에서

 

그 다음 미들웨어 함수에 대한 접근을 가진다.

 

미들웨어 함수를 통하여 myLogger를 처리하여 

 

next라는 이름의 변수로 그 다음 미들웨어 함수를 호출해준다.

 

var express = require('express')
var app = express()

var myLogger = function (req, res, next) {
  console.log('LOGGED')
  next()
}

app.use(myLogger)

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000)

myLogger가 호출되면 LOGGED라는 문자를 나타내게 만들어 준다.

 

express는 기존의 Node.js만으로 복잡한 웹서버를 구축할 수 없기 때문에

 

자주 사용된다.

 

출처: https://expressjs.com/ko/