Node.js_ Express

Adela·2020년 11월 16일
0

Node.js

목록 보기
3/7
post-thumbnail

Express "framework for NodeJS"

https://expressjs.com/en/starter/installing.html
공식문서가 아주 친절한 편 (개인적인 생각)

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}`)
})

미들웨어(middleware)

처리가 끝날 때까지 연결되어 있는 것, 완료될 때까지 어떤 기능(함수)을 실행하는 것.

라우트를 예를 들면
각 라우트는 하나 이상의 핸들러 함수를 가질 수 있으며, 이러한 함수는 라우트가 일치할 때 실행된다.

// 구조 app.METHOD(PATH, HANDLER)

app.get("/", handleSlash);

root /를 찾으면 (요청) handleSlash를 실행하여 응답한다.

express에서 모든 함수는 middleware가 될 수 있다. 또, 원하는 만큼 미들웨어를 가질 수 있다.

/* 미들웨어로 장착할 betweenSlash를
유저의 요청과 응답 사이에 두고 계속 처리할 수 있는 권한을 준다. */

// '/'라우팅에 대한 미들웨어 betweenSlash
app.get("/", betweenSlash, handleSlash);

또는
app.use(betweenSlash) // 라인순서를 잘 맞추면 모든 라우팅에 대한 미들웨어로도 사용할 수 있다.
app.get("/", handleSlash);

const betweenSlash = (req, res, next) => {
  console.log("Between");
  next(); // 이 부분이 다음 처리 할 미들웨어(= handleSlash)를 호출하는 부분이다.
}

위의 코드가 실행되면 해당 /로 갔을 때 betweenSlash가 실행되고 handleSlash도 실행되어 동작이 나타난다.

응답에서 리턴하는(res.send(nothing))게 없다면 반환할 게 없어서 무한로딩에 걸린다.

미들웨어를 잘 사용하면 어떤 main 동작에 sub되는 기능을 구현할 수 있을 것 같다.

미들웨어 함수가 res.send(something)을 반환하면 연결을 끊는다.

미들웨어의 위치

미들웨어 작동 후 route 처리

app.use(middleware1);
app.use(middleware2);
... 원하는 만큼 미들웨어 작성

app.get("/", func1);
app.get("/profile", func2);

app.listen(PORT, printConnection);

한가지 route에 대한 미들웨어

app.get("/", func1); // middleware1가 적용 되지 않음, 실행 되기 전 이므로

app.use(middleware1); 

app.get("/profile", func2);
// profile로 가기 전에만 middleware1 실행

app.listen(PORT, printConnection);
profile
👩🏼‍💻 SWE (FE)

0개의 댓글

관련 채용 정보